internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: microsoft/Qcodes

Issue:
default Instrument get_idn returns a warning
For any `Instrument` that does not have a `self.ask('*IDN?')` a warning is generated. This is inconvenient for all derived classes that do not have a VISA interface.

The warning is generated here:

https://github.com/QCoDeS/Qcodes/blob/master/qcodes/instrument/base.py#L130

A minimal example:
```
from qcodes import Instrument

class dummy(Instrument):
    pass

d=dummy(name='test')
idn=d.get_idn()
```
Can we remove the warning (or change it into a `logging.info`)?

@giulioungaretti 


Discussion:
I agree with this. I think that the connect message (that raises this warning)  can be very useful. 
I would propose that we solve this problem by implementing a default `.get_idn()` that returns `self.name` (in the format that works with the message). 
@peendebak @AdriaanRol, yes agree. I guess this was written with the assumption that **all** instruments have the arcane visa IDN command.

Not sure what's best:
  - 1 move it to VISA base class
  - 2 change to info (but it's kind of meant to be a warning ?) 
  - 3 change to info, but  return a sane default instead

I would go for 1, but we have to check how many instruments inherit from IP and speak visa ! 

@giulioungaretti , Another quite common use case for us is to have virtual or meta instruments. These talk to lower level instruments and generally do not have an IDN command (as they only exist in python). I think a sane default would make most sense. 

That would still be consistent with -1 but would also require a sane connect message. 
@giulioungaretti @AdriaanRol Shall I create a PR with option 3). A default that we use right now is:
```
        IDN = {'vendor': None, 'model': self.name,
               'serial': None, 'firmware': None}
```

@peendebak that would be really awesome! 

Resolving patch:
diff --git a/qcodes/instrument/base.py b/qcodes/instrument/base.py
--- a/qcodes/instrument/base.py
+++ b/qcodes/instrument/base.py
@@ -127,8 +127,8 @@ def get_idn(self):
             if len(idparts) < 4:
                 idparts += [None] * (4 - len(idparts))
         except:
-            logging.warn('Error getting or interpreting *IDN?: ' + repr(idstr))
-            idparts = [None, None, None, None]
+            logging.debug('Error getting or interpreting *IDN?: ' + repr(idstr))
+            idparts = [None, self.name, None, None]
 
         # some strings include the word 'model' at the front of model
         if str(idparts[1]).lower().startswith('model'):


Test patch:
Repository: microsoft/Qcodes

Issue:
validate fails with IVVI driver
The IVVI driver internally converts any `set` value to a integer number for setting (12 or 16 bit I think). For example -800 is converted to -800.0305180.
When a validator is set to range [-800, 400] a `set` with value -800 works fine, but then a `set` to -700 fails because -800.0305180 is not in the valid range.
### Steps to reproduce
1. Create an IVVI instrument and set validator range to [-800, 400]
2. Do ivvi.dac1.set(-800)
3. Do iivi.dac1.get()

I am not sure where to solve this one. The actual error is generated in `self.validate(start_value)` (see code snippet below. We could argue that the current value of a parameter is _always_ allowed, but there might be exceptions when multiple parameters use the same instrument.

``` python
    def _sweep_steps(self, value):
        oldest_ok_val = datetime.now() - timedelta(seconds=self._max_val_age)
        state = self._latest()
        if state['ts'] is None or state['ts'] < oldest_ok_val:
            start_value = self.get()
        else:
            start_value = state['value']

        self.validate(start_value)
```

@AdriaanRol @dbouman1 @CJvanDiepen @alexcjohnson 



Discussion:

Resolving patch:
diff --git a/qcodes/instrument_drivers/QuTech/IVVI.py b/qcodes/instrument_drivers/QuTech/IVVI.py
--- a/qcodes/instrument_drivers/QuTech/IVVI.py
+++ b/qcodes/instrument_drivers/QuTech/IVVI.py
@@ -468,6 +468,32 @@ def get_func():
             return fun(ch)
         return get_func
 
+    def adjust_parameter_validator(self, param):
+        """Adjust the parameter validator range based on the dac resolution.
+
+        The dac's of the IVVI have a finite resolution. If the validator range
+        min and max values are not values the dac's can actually have, then it
+        can occur that a set command results in the dac's going to a value just
+        outside the validator range. Adjusting the validators with this
+        function prevents that.
+
+        Args:
+            param (StandardParameter): a dac of the IVVI instrument
+        """
+        if type(param._vals) is not Numbers:
+            raise Exception('Only the Numbers validator is supported.')
+        min_val = param._vals._min_value
+        max_val = param._vals._max_value
+        min_val_pol_corr = min_val - self.pol_num[int(param.name[3:]) - 1]
+        max_val_pol_corr = max_val - self.pol_num[int(param.name[3:]) - 1]
+        min_val_bytes = self._mvoltage_to_bytes(min_val_pol_corr)
+        min_val_upd = (min_val_bytes[0] * 256 + min_val_bytes[1]) / \
+            65535.0 * self.Fullrange + self.pol_num[int(param.name[3:]) - 1]
+        max_val_bytes = self._mvoltage_to_bytes(max_val_pol_corr)
+        max_val_upd = (max_val_bytes[0] * 256 + max_val_bytes[1]) / \
+            65535.0 * self.Fullrange + self.pol_num[int(param.name[3:]) - 1]
+        param._vals = Numbers(min_val_upd, max_val_upd)
+
 '''
 RS232 PROTOCOL
 -----------------------


Test patch:
Repository: microsoft/Qcodes

Issue:
Keithley2600 driver broken after commit 460c93c71506213102e56d3ea0c518723666d56a

### Steps to reproduce
1. Connect Keithley 2600
2. ask it for output status or mode
3. doh

### Expected behaviour
tell me what i asked for

### Actual behaviour
error because parsing fails
issue introduced in  commit 460c93c71506213102e56d3ea0c518723666d56a (@alexcjohnson)


### System
**operating system**
W10
**qcodes branch**
master
**qcodes commit**
177f8201b3778c0071c60d4e4c658449284e1a6c 


Discussion:

Resolving patch:
diff --git a/qcodes/instrument_drivers/tektronix/Keithley_2600.py b/qcodes/instrument_drivers/tektronix/Keithley_2600.py
--- a/qcodes/instrument_drivers/tektronix/Keithley_2600.py
+++ b/qcodes/instrument_drivers/tektronix/Keithley_2600.py
@@ -19,20 +19,26 @@ def __init__(self, name, address, channel, **kwargs):
         super().__init__(name, address, terminator='\n', **kwargs)
         self._channel = channel
 
-        self.add_parameter('volt', get_cmd='measure.v()',
-                           get_parser=float, set_cmd='source.levelv={:.12f}',
+        self.add_parameter('volt',
+                           get_cmd='measure.v()',
+                           get_parser=float,
+                           set_cmd='source.levelv={:.12f}',
                            label='Voltage',
                            unit='V')
-        self.add_parameter('curr', get_cmd='measure.i()',
-                           get_parser=float, set_cmd='source.leveli={:.12f}',
+        self.add_parameter('curr',
+                           get_cmd='measure.i()',
+                           get_parser=float,
+                           set_cmd='source.leveli={:.12f}',
                            label='Current',
                            unit='A')
         self.add_parameter('mode',
                            get_cmd='source.func',
+                           get_parser=float,
                            set_cmd='source.func={:d}',
                            val_mapping={'current': 0, 'voltage': 1})
         self.add_parameter('output',
                            get_cmd='source.output',
+                           get_parser=float,
                            set_cmd='source.output={:d}',
                            val_mapping={'on':  1, 'off': 0})
         # Source range


Test patch:
Repository: microsoft/Qcodes

Issue:
visa_handle.clear on instantiation causes some instruments to freeze
The use of visa_handle.clear on the instantiation of a VISA instrument causes some instruments to lock up. In particular I've noticed for SERIAL instruments, this command spews some garbage on the serial port that requires the instrument to be reset before it is possible to use it again.

### Steps to reproduce
1. Plug in a buggy instrument and instantiate an instance of it.

### Actual behaviour
The instrument freezes

### System
Win 7
Using the Harvard DecaDAC
2b6d72b


Discussion:

Resolving patch:
diff --git a/qcodes/instrument/visa.py b/qcodes/instrument/visa.py
--- a/qcodes/instrument/visa.py
+++ b/qcodes/instrument/visa.py
@@ -1,10 +1,11 @@
 """Visa instrument driver based on pyvisa."""
 import visa
+import pyvisa.constants as vi_const
+import pyvisa.resources
 
 from .base import Instrument
 import qcodes.utils.validators as vals
 
-
 class VisaInstrument(Instrument):
 
     """
@@ -74,7 +75,13 @@ def set_address(self, address):
 
         self.visa_handle = resource_manager.open_resource(address)
 
-        self.visa_handle.clear()
+        # Serial instruments have a separate flush method to clear their buffers
+        # which behaves differently to clear. This is particularly important
+        # for instruments which do not support SCPI commands.
+        if isinstance(self.visa_handle, pyvisa.resources.SerialInstrument):
+            self.visa_handle.flush(vi_const.VI_READ_BUF_DISCARD | vi_const.VI_WRITE_BUF_DISCARD)
+        else:
+            self.visa_handle.clear()
         self._address = address
 
     def set_terminator(self, terminator):


Test patch:
Repository: microsoft/Qcodes

Issue:
subplots do not work with MatPlot
A minimal example:
```
import qcodes
import qcodes.tests.data_mocks

ds=qcodes.tests.data_mocks.DataSet1D()
p = qcodes.MatPlot()
p.add(ds.default_parameter_array() )

p = qcodes.MatPlot(subplots=(2,2))
p.add(ds.default_parameter_array()) # fail
p.add(ds.default_parameter_array(), subplot=1) # fail
```

@giulioungaretti 
subplots do not work with MatPlot
A minimal example:
```
import qcodes
import qcodes.tests.data_mocks

ds=qcodes.tests.data_mocks.DataSet1D()
p = qcodes.MatPlot()
p.add(ds.default_parameter_array() )

p = qcodes.MatPlot(subplots=(2,2))
p.add(ds.default_parameter_array()) # fail
p.add(ds.default_parameter_array(), subplot=1) # fail
```

@giulioungaretti 


Discussion:

Resolving patch:
diff --git a/qcodes/plots/qcmatplotlib.py b/qcodes/plots/qcmatplotlib.py
--- a/qcodes/plots/qcmatplotlib.py
+++ b/qcodes/plots/qcmatplotlib.py
@@ -53,12 +53,16 @@ def _init_plot(self, subplots=None, figsize=None, num=None):
 
         if isinstance(subplots, Mapping):
             self.fig, self.subplots = plt.subplots(figsize=figsize, num=num,
-                                                   **subplots)
+                                                   **subplots, squeeze=False)
         else:
             self.fig, self.subplots = plt.subplots(*subplots, num=num,
-                                                   figsize=figsize)
-        if not hasattr(self.subplots, '__len__'):
-            self.subplots = (self.subplots,)
+                                                   figsize=figsize, squeeze=False)
+
+        # squeeze=False ensures that subplots is always a 2D array independent of the number
+        # of subplots.
+        # However the qcodes api assumes that subplots is always a 1D array
+        # so flatten here
+        self.subplots = self.subplots.flatten()
 
         self.title = self.fig.suptitle('')
 


Test patch:
Repository: microsoft/Qcodes

Issue:
Adding a Keysight 344658 to a station is slow
Similar to the QDac issue., The snapshot probably needs to be speed up



Discussion:
This is caused by a keysight not having the DIG option installed. 

The sample_count_pretrigger parameter needs to be wrapped in a `if DIG:` clause 

Resolving patch:
diff --git a/qcodes/instrument_drivers/Keysight/Keysight_34465A.py b/qcodes/instrument_drivers/Keysight/Keysight_34465A.py
--- a/qcodes/instrument_drivers/Keysight/Keysight_34465A.py
+++ b/qcodes/instrument_drivers/Keysight/Keysight_34465A.py
@@ -269,18 +269,19 @@ def __init__(self, name, address, DIG=False, utility_freq=50, silent=False,
                                                vals.Enum('MIN', 'MAX', 'DEF')),
                            get_parser=int)
 
-        self.add_parameter('sample_count_pretrigger',
-                           label='Sample Pretrigger Count',
-                           set_cmd='SAMPle:COUNt:PRETrigger {}',
-                           get_cmd='SAMPle:COUNt:PRETrigger?',
-                           vals=vals.MultiType(vals.Numbers(0, 2e6-1),
-                                               vals.Enum('MIN', 'MAX', 'DEF')),
-                           get_parser=int,
-                           docstring=('Allows collection of the data '
-                                      'being digitized the trigger. Reserves '
-                                      'memory for pretrigger samples up to the'
-                                      ' specified num. of pretrigger samples.')
-                           )
+        if DIG:
+            self.add_parameter('sample_count_pretrigger',
+                               label='Sample Pretrigger Count',
+                               set_cmd='SAMPle:COUNt:PRETrigger {}',
+                               get_cmd='SAMPle:COUNt:PRETrigger?',
+                               vals=vals.MultiType(vals.Numbers(0, 2e6-1),
+                                                   vals.Enum('MIN', 'MAX', 'DEF')),
+                               get_parser=int,
+                               docstring=('Allows collection of the data '
+                                          'being digitized the trigger. Reserves '
+                                          'memory for pretrigger samples up to the'
+                                          ' specified num. of pretrigger samples.')
+                               )
 
         self.add_parameter('sample_source',
                            label='Sample Timing Source',


Test patch:
Repository: microsoft/Qcodes

Issue:
Dont auto limit colorbar. 
The user may have done this on purpose to filter outlier

* Replace wrappers in qdev-dk with call to new function
* Make autolimit of colorbars optional or disable it completely


Discussion:
If the purpose was to filter outliers we could consider implementing, this as a functionality. In my experience a really convenient way to automatically filter outliers is apply a percentile scale, eg setting the colorscale such that the upper and lower 1%  of the number of points are excluded.

Resolving patch:
diff --git a/qcodes/plots/pyqtgraph.py b/qcodes/plots/pyqtgraph.py
--- a/qcodes/plots/pyqtgraph.py
+++ b/qcodes/plots/pyqtgraph.py
@@ -479,10 +479,13 @@ def setGeometry(self, x, y, w, h):
         """ Set geometry of the plotting window """
         self.win.setGeometry(x, y, w, h)
 
-    def autorange(self):
+    def autorange(self, reset_colorbar: bool=False):
         """
         Auto range all limits in case they were changed during interactive
         plot. Reset colormap if changed and resize window to original size.
+        Args:
+            reset_colorbar: Should the limits and colorscale of the colorbar
+                be reset. Off by default
         """
         for subplot in self.subplots:
             vBox = subplot.getViewBox()
@@ -492,7 +495,8 @@ def autorange(self):
         for trace in self.traces:
             if 'plot_object' in trace.keys():
                 if (isinstance(trace['plot_object'], dict) and
-                            'hist' in trace['plot_object'].keys()):
+                            'hist' in trace['plot_object'].keys() and
+                            reset_colorbar):
                     cmap = trace['plot_object']['cmap']
                     maxval = trace['config']['z'].max()
                     minval = trace['config']['z'].min()
@@ -517,8 +521,7 @@ def fixUnitScaling(self, startranges: Optional[Dict[str, Dict[str, Union[float,i
                          {'paramtername': {max: value, min:value}}
         """
         axismapping = {'x': 'bottom',
-                       'y': 'left',
-                       'z': 'right'}
+                       'y': 'left'}
         standardunits = self.standardunits
         for i, plot in enumerate(self.subplots):
             # make a dict mapping axis labels to axis positions
diff --git a/qcodes/plots/qcmatplotlib.py b/qcodes/plots/qcmatplotlib.py
--- a/qcodes/plots/qcmatplotlib.py
+++ b/qcodes/plots/qcmatplotlib.py
@@ -451,7 +451,5 @@ def scale_formatter(i, pos, scale):
                                 new_label)
                         else:
                             subplot.qcodes_colorbar.formatter = tx
-                            subplot.qcodes_colorbar.ax.yaxis.set_major_formatter(
-                                tx)
                             subplot.qcodes_colorbar.set_label(new_label)
                             subplot.qcodes_colorbar.update_ticks()


Test patch:
Repository: microsoft/Qcodes

Issue:
missing dependency`jsonschema` in requirements.txt
The latest pip installable version of QCoDeS does not list jsonschema as a dependency but requires it. 

This problem came to light when running tests on a project that depeneds on QCoDeS. Part of my build script installs qcodes (pip install qcodes). Importing qcodes then raises an exception because jsonschema is missing. 


Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -61,7 +61,8 @@ def readme():
           'numpy>=1.10',
           'pyvisa>=1.8',
           'h5py>=2.6',
-          'websockets>=3.2,<3.4'
+          'websockets>=3.2,<3.4',
+          'jsonschema'
       ],
 
       test_suite='qcodes.tests',


Test patch:
Repository: microsoft/Qcodes

Issue:
internal data of String validator breaks AWG5014
In PR #859 new variables `._valid_values` are added to the `String` validator. The default validator object `qcodes.utils.validators.String()` now has a size of 1 GB.

The `AWG5014` driver uses the `String` validator four times, so the driver now is 4GB. If one reloads the driver 8 GB is occupied, which crashes a system with limited amount of RAM.

https://github.com/QCoDeS/Qcodes/blob/master/qcodes/instrument_drivers/tektronix/AWG5014.py#L326

I am not sure how the `._valid_values` field is used, but I think it does not make a lot of sens for a `String`. Can we set the `_valid_values` field to `None` as a solution?

@WilliamHPNielsen @AdriaanRol @jenshnielsen @lucblom





Discussion:

Resolving patch:
diff --git a/qcodes/utils/validators.py b/qcodes/utils/validators.py
--- a/qcodes/utils/validators.py
+++ b/qcodes/utils/validators.py
@@ -147,7 +147,7 @@ def __init__(self, min_length=0, max_length=BIGSTRING):
         else:
             raise TypeError('max_length must be a positive integer '
                             'no smaller than min_length')
-        self._valid_values = ['.'*min_length, '.'*max_length]
+        self._valid_values = ['.'*min_length]
 
     def validate(self, value, context=''):
         if not isinstance(value, str):


Test patch:
Repository: microsoft/Qcodes

Issue:
error when saving to drive other than current path
This is due to windows handling of drives. A minimal example:
``` python
import qcodes,os

datadir = r'd:\Temp'
qcodes.DataSet.default_io = qcodes.DiskIO(datadir)

p=qcodes.Parameter('p', set_cmd=None)
q=qcodes.Parameter('q', set_cmd=None)
ds=qcodes.Loop(p[0:10:1]).each(q).run() # fine
 
qcodes.DataSet.default_io = qcodes.DiskIO(r'c:\Temp')

ds=qcodes.Loop(p[0:10:1]).each(p).run() # error
```
This generates the error `ValueError: path is on mount 'd:', start on mount 'c:'`

Also see https://bugs.python.org/issue7195




Discussion:

Resolving patch:
diff --git a/qcodes/data/io.py b/qcodes/data/io.py
--- a/qcodes/data/io.py
+++ b/qcodes/data/io.py
@@ -141,7 +141,7 @@ def to_location(self, path):
             location (str): the location string corresponding to this path.
         """
         if self.base_location:
-            return os.path.relpath(path, self.base_location)
+            return os.path.join(self.base_location, path)
         else:
             return path
 


Test patch:
Repository: microsoft/Qcodes

Issue:
Closing an IPInstrument cases an AttributeError
### Steps to reproduce
1. Open an `IPInstrument` (such as a AMI430 magnet)
2. Call the `close` method on the `IPInstrument`

### Actual behaviour
```pytb
Traceback (most recent call last):

  File "<ipython-input-53-d6c9fed2956e>", line 5, in <module>
    instr.close()

  File "c:\users\ld2007\documents\qcodes\qcodes\instrument\ip.py", line 154, in close
    super().close()

  File "c:\users\ld2007\documents\qcodes\qcodes\instrument\base.py", line 461, in close
    self.remove_instance(self)

  File "c:\users\ld2007\documents\qcodes\qcodes\instrument\base.py", line 538, in remove_instance
    if wr in cls._instances:

AttributeError: type object 'AMI430' has no attribute '_instances'
```

### System
Issue as of 85b3958d177f4770224be0739c97f5b5ff202cef



Discussion:

Resolving patch:
diff --git a/qcodes/instrument/base.py b/qcodes/instrument/base.py
--- a/qcodes/instrument/base.py
+++ b/qcodes/instrument/base.py
@@ -535,7 +535,7 @@ def remove_instance(cls, instance: 'Instrument') -> None:
             The instance to remove
         """
         wr = weakref.ref(instance)
-        if wr in cls._instances:
+        if wr in getattr(cls, "_instances", []):
             cls._instances.remove(wr)
 
         # remove from all_instruments too, but don't depend on the


Test patch: