nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: hoburg/gpkit
Pull request #727 (2016-05-29 21:20:31)

Make it possible to pass arguments to cvxopt solver
Fixed a bug and added a test. See inline comments for more details.


Patch:
diff --git a/gpkit/_cvxopt.py b/gpkit/_cvxopt.py
index a7b72d9..752b412 100644
--- a/gpkit/_cvxopt.py
+++ b/gpkit/_cvxopt.py
@@ -2,10 +2,8 @@
 from cvxopt import solvers, spmatrix, matrix, log
 
 
-def cvxoptimize_fn(options=None):
-    "Return a cvxopt solve function for a particular set of options."
-    if options:
-        solvers.options.update(options)
+def cvxoptimize_fn():
+    "Return a cvxopt solve function"
     gpsolver = solvers.gp
 
     # pylint: disable=unused-argument
diff --git a/gpkit/geometric_program.py b/gpkit/geometric_program.py
index 7626926..c848d4d 100644
--- a/gpkit/geometric_program.py
+++ b/gpkit/geometric_program.py
@@ -152,7 +152,7 @@ class GeometricProgram(NomialData):
 
             if solver == "cvxopt":
                 from ._cvxopt import cvxoptimize_fn
-                solverfn = cvxoptimize_fn(*args, **kwargs)
+                solverfn = cvxoptimize_fn()
             elif solver == "mosek_cli":
                 from ._mosek import cli_expopt
                 solverfn = cli_expopt.imize_fn(*args, **kwargs)


Test patch:
diff --git a/gpkit/tests/t_model.py b/gpkit/tests/t_model.py
index 1e08ea6..79f596d 100644
--- a/gpkit/tests/t_model.py
+++ b/gpkit/tests/t_model.py
@@ -390,10 +390,22 @@ class TestSP(unittest.TestCase):
         self.assertEqual(first_gp_constr_posy.exp[x.key], -1./3)
 
 
-TEST_CASES = [TestGP, TestSP]
+class TestModelSolverSpecific(unittest.TestCase):
+    """test cases run only for specific solvers"""
+    def test_cvxopt_kwargs(self):
+        if "cvxopt" not in settings["installed_solvers"]:
+            return
+        x = Variable("x")
+        m = Model(x, [x >= 12])
+        # make sure it's possible to pass the kktsolver option to cvxopt
+        sol = m.solve(solver="cvxopt", verbosity=0, kktsolver="ldl")
+        self.assertAlmostEqual(sol["cost"], 12., NDIGS["cvxopt"])
+
+
+TESTS = [TestModelSolverSpecific]
+MULTI_SOLVER_TESTS = [TestGP, TestSP]
 
-TESTS = []
-for testcase in TEST_CASES:
+for testcase in MULTI_SOLVER_TESTS:
     for solver in settings["installed_solvers"]:
         if solver:
             test = type(testcase.__name__+"_"+solver,
Repository: hoburg/gpkit
Pull request #893 (2016-09-12 23:46:16)

KeyDict: failed __getitem__ causes state change
Found an issue where attempting to access a missing key from a KeyDict causes a state change where future updates and calls to `in` act incorrectly.

MWE is the attached test (also added as a commit to this PR):

```python
    def test_failed_getattr(self):
        kd = KeyDict()
        with self.assertRaises(KeyError):
            _ = kd["waldo"]
            # a failed __getitem__ causes potential state change (issue 893)
        # TODO uncomment next assertNotIn after getting rest of test working
        # self.assertNotIn("waldo", kd)
        kd.update({"waldo": 5})
        res = kd["waldo"]
        self.assertEqual(res, 5)
        self.assertIn("waldo", kd)
```

Issue can arise in interactive sessions when someone checks whether something is in a Models'
 substitutions dict, gets a KeyError, and then cannot update that key from then onwards.

whoburg: @bqpd, priority issue.
whoburg: Just checked, this issue exists back at 780750bdc7fd8070120c6312926dfec43253e5af (a month ago), so not a result of any of the recent activity.
bqpd: @whoburg, fix ready for review
whoburg: Looks great. Added one commit. And just confirmed that this does resolve the higher-level problem I observed with @mjburton11 today that led to finding this bug.

Planning to merge when all tests pass.
whoburg: actually going to push one more cosmetic commit. Will squash all these.
whoburg: @bqpd following good protocol, how about you merge this since I added commits.
bqpd: Will do!

Patch:
diff --git a/gpkit/keydict.py b/gpkit/keydict.py
index 1f2daf2..909d339 100644
--- a/gpkit/keydict.py
+++ b/gpkit/keydict.py
@@ -89,6 +89,7 @@ class KeyDict(dict):
         key, idx = self.parse_and_index(key)
         keys = self.keymap[key]
         if not keys:
+            del self.keymap[key] # remove blank entry added due to defaultdict
             raise KeyError("%s was not found." % key)
         values = []
         for key in keys:


Test patch:
diff --git a/gpkit/tests/t_keydict.py b/gpkit/tests/t_keydict.py
index 3f254a1..df0230e 100644
--- a/gpkit/tests/t_keydict.py
+++ b/gpkit/tests/t_keydict.py
@@ -26,6 +26,17 @@ class TestKeyDict(unittest.TestCase):
         self.assertEqual(kd["x_motor"], 52)
         self.assertNotIn("x_someothermodelname", kd)
 
+    def test_failed_getattr(self):
+        kd = KeyDict()
+        with self.assertRaises(KeyError):
+            _ = kd["waldo"]
+            # issue 893: failed __getitem__ caused state change
+        self.assertNotIn("waldo", kd)
+        kd.update({"waldo": 5})
+        res = kd["waldo"]
+        self.assertEqual(res, 5)
+        self.assertIn("waldo", kd)
+
     def test_dictlike(self):
         kd = KeyDict()
         kd["a string key"] = "a string value"
Repository: SpikeInterface/spikeinterface
Pull request #980 (2022-09-30 10:29:55)

remove scipy from core.


Patch:
diff --git a/spikeinterface/core/recording_tools.py b/spikeinterface/core/recording_tools.py
index 93eaed0f4..48cf999c0 100644
--- a/spikeinterface/core/recording_tools.py
+++ b/spikeinterface/core/recording_tools.py
@@ -57,11 +57,11 @@ def get_channel_distances(recording):
     """
     Distance between channel pairs
     """
-    # TODO SAM: convert to numpy
-    import scipy
     locations = recording.get_channel_locations()
     
-    channel_distances = scipy.spatial.distance.cdist(locations, locations, metric='euclidean')
+
+    channel_distances = np.linalg.norm(locations[:, np.newaxis] - locations[np.newaxis, :], axis=2)
+
     return channel_distances
 
 


Test patch:
diff --git a/spikeinterface/core/tests/test_recording_tools.py b/spikeinterface/core/tests/test_recording_tools.py
index d3319894b..8a2af551f 100644
--- a/spikeinterface/core/tests/test_recording_tools.py
+++ b/spikeinterface/core/tests/test_recording_tools.py
@@ -3,7 +3,7 @@ import numpy as np
 from spikeinterface.core.testing_tools import generate_recording
 
 from spikeinterface.core.recording_tools import (get_random_data_chunks, get_chunk_with_margin,
-                                                 get_closest_channels, get_noise_levels)
+                                                 get_closest_channels, get_channel_distances, get_noise_levels)
 
 
 def test_get_random_data_chunks():
@@ -11,12 +11,14 @@ def test_get_random_data_chunks():
     chunks = get_random_data_chunks(rec, num_chunks_per_segment=50, chunk_size=500, seed=0)
     assert chunks.shape == (50000, 1)
 
+    
 
 def test_get_closest_channels():
     rec = generate_recording(num_channels=32, sampling_frequency=1000., durations=[0.1])
     closest_channels_inds, distances = get_closest_channels(rec)
     closest_channels_inds, distances = get_closest_channels(rec, num_channels=4)
-
+    
+    dist = get_channel_distances(rec)
 
 def test_get_noise_levels():
     rec = generate_recording(num_channels=2, sampling_frequency=1000., durations=[60.])
@@ -83,6 +85,6 @@ def test_get_chunk_with_margin():
     
 
 if __name__ == '__main__':
-    test_get_random_data_chunks()
-    # test_get_closest_channels()
+    # test_get_random_data_chunks()
+    test_get_closest_channels()
     # test_get_noise_levels()
Repository: SpikeInterface/spikeinterface
Pull request #1055 (2022-11-03 16:07:13)

Fix crash wvf_extractor with empty sorting
Fixed a crash in `WaveformExtractor.run_extract_waveforms()` with an empty sorting.


Patch:
diff --git a/spikeinterface/core/waveform_extractor.py b/spikeinterface/core/waveform_extractor.py
index 07728896d..5ac07fdf5 100644
--- a/spikeinterface/core/waveform_extractor.py
+++ b/spikeinterface/core/waveform_extractor.py
@@ -830,7 +830,7 @@ class WaveformExtractor:
         
         spikes = []
         for segment_index in range(self.sorting.get_num_segments()):
-            num_in_seg = np.sum([selected_spikes[unit_id][segment_index].size for unit_id in unit_ids])
+            num_in_seg = np.sum([selected_spikes[unit_id][segment_index].size for unit_id in unit_ids], dtype=np.int64)
             spike_dtype = [('sample_ind', 'int64'), ('unit_ind', 'int64'), ('segment_ind', 'int64')]
             spikes_ = np.zeros(num_in_seg,  dtype=spike_dtype)
             pos = 0


Test patch:
diff --git a/spikeinterface/core/tests/test_waveform_extractor.py b/spikeinterface/core/tests/test_waveform_extractor.py
index 290bfe232..58625d005 100644
--- a/spikeinterface/core/tests/test_waveform_extractor.py
+++ b/spikeinterface/core/tests/test_waveform_extractor.py
@@ -5,7 +5,7 @@ import numpy as np
 import platform
 
 
-from spikeinterface.core.testing_tools import generate_recording, generate_sorting
+from spikeinterface.core.testing_tools import generate_recording, generate_sorting, NumpySorting
 from spikeinterface import WaveformExtractor, BaseRecording, extract_waveforms
 
 
@@ -306,6 +306,20 @@ def test_portability():
         assert np.allclose(wf, wf_loaded)
 
 
+def test_empty_sorting():
+    sf = 30000
+    num_channels = 2
+
+    recording = generate_recording(num_channels=num_channels, sampling_frequency=sf, durations=[15.32])
+    sorting = NumpySorting.from_dict({}, sf)
+
+    folder = cache_folder / "empty_sorting"
+    wvf_extractor = extract_waveforms(recording, sorting, folder, allow_unfiltered=True)
+
+    assert len(wvf_extractor.unit_ids) == 0
+    assert wvf_extractor.get_all_templates().shape == (0, wvf_extractor.nsamples, num_channels)
+
+
 if __name__ == '__main__':
     # test_WaveformExtractor()
     # test_extract_waveforms()