Changeset 44a698c in sasview for src/sas/sascalc


Ignore:
Timestamp:
Mar 12, 2019 7:15:06 AM (5 years ago)
Author:
Piotr Rozyczko <piotr.rozyczko@…>
Branches:
ESS_GUI_sync_sascalc
Parents:
390494d
Message:

Cherry-picked changes from py37-sascalc branch.

Location:
src/sas/sascalc
Files:
14 edited

Legend:

Unmodified
Added
Removed
  • src/sas/sascalc/calculator/instrument.py

    rb8080e1 r44a698c  
    128128            self.size = 0 
    129129        else: 
    130             self.size = size 
     130            # TODO: Make sure detector size is number of pixels 
     131            # Could be detector dimensions in e.g., mm, but 
     132            # the resolution calculator assumes it is pixels. 
     133            # Being pixels, it has to be integers rather than float 
     134            self.size = [int(s) for s in size] 
    131135            validate(size[0]) 
    132136 
  • src/sas/sascalc/calculator/sas_gen.py

    rb8080e1 r44a698c  
    304304                z_dir2 *= z_dir2 
    305305                mask = (x_dir2 + y_dir2 + z_dir2) <= 1.0 
    306             except Exception: 
    307                 logger.error(sys.exc_value) 
     306            except Exception as exc: 
     307                logger.error(exc) 
    308308        self.output = MagSLD(self.pos_x[mask], self.pos_y[mask], 
    309309                             self.pos_z[mask], self.sld_n[mask], 
     
    600600                        y_lines.append(y_line) 
    601601                        z_lines.append(z_line) 
    602                 except Exception: 
    603                     logger.error(sys.exc_value) 
     602                except Exception as exc: 
     603                    logger.error(exc) 
    604604 
    605605            output = MagSLD(pos_x, pos_y, pos_z, sld_n, sld_mx, sld_my, sld_mz) 
     
    691691                            _vol_pix = float(toks[7]) 
    692692                            vol_pix = np.append(vol_pix, _vol_pix) 
    693                         except Exception: 
     693                        except Exception as exc: 
    694694                            vol_pix = None 
    695                     except Exception: 
     695                    except Exception as exc: 
    696696                        # Skip non-data lines 
    697                         logger.error(sys.exc_value) 
     697                        logger.error(exc) 
    698698            output = MagSLD(pos_x, pos_y, pos_z, sld_n, 
    699699                            sld_mx, sld_my, sld_mz) 
  • src/sas/sascalc/corfunc/corfunc_calculator.py

    r6ae7466 r44a698c  
    3030            self.start = start 
    3131            self.stop = stop 
    32             self._lastx = [] 
    33             self._lasty = [] 
     32            self._lastx = np.empty(0, dtype='d') 
     33            self._lasty = None 
    3434 
    3535        def __call__(self, x): 
    3636            # If input is a single number, evaluate the function at that number 
    3737            # and return a single number 
    38             if type(x) == float or type(x) == int: 
     38            if isinstance(x, (float, int)): 
    3939                return self._smoothed_function(np.array([x]))[0] 
    4040            # If input is a list, and is different to the last input, evaluate 
     
    4242            # the function was called, return the result that was calculated 
    4343            # last time instead of explicity evaluating the function again. 
    44             elif self._lastx == [] or x.tolist() != self._lastx.tolist(): 
    45                 self._lasty = self._smoothed_function(x) 
    46                 self._lastx = x 
     44            if not np.array_equal(x, self._lastx): 
     45                self._lastx, self._lasty = x, self._smoothed_function(x) 
    4746            return self._lasty 
    4847 
     
    8887        # Only process data of the class Data1D 
    8988        if not issubclass(data.__class__, Data1D): 
    90             raise ValueError("Correlation function cannot be computed with 2D Data.") 
     89            raise ValueError("Correlation function cannot be computed with 2D data.") 
    9190 
    9291        # Prepare the data 
  • src/sas/sascalc/corfunc/transform_thread.py

    ra859f99 r44a698c  
    4545            # gamma3(R) = 1/R int_{0}^{R} gamma1(x) dx 
    4646            # trapz uses the trapezium rule to calculate the integral 
    47             mask = xs <= 200.0 # Only calculate gamma3 up to x=200 (as this is all that's plotted) 
     47            mask = xs <= 1000.0 # Only calculate gamma3 up to x=1000 (as this is all that's plotted) 
    4848            # gamma3 = [trapz(gamma1[:n], xs[:n])/xs[n-1] for n in range(2, len(xs[mask]) + 1)]j 
    4949            # gamma3.insert(0, 1.0) # Gamma_3(0) is defined as 1 
     
    7979 
    8080        transform1 = Data1D(xs, gamma1) 
    81         transform3 = Data1D(xs[xs <= 200], gamma3) 
     81        transform3 = Data1D(xs[xs <= 1000], gamma3) 
    8282        idf = Data1D(xs, idf) 
    8383 
  • src/sas/sascalc/data_util/calcthread.py

    r574adc7 r44a698c  
    66from __future__ import print_function 
    77 
    8 import traceback 
    98import sys 
    109import logging 
     10import traceback 
     11from time import sleep 
     12 
    1113try: 
    1214    import _thread as thread 
    1315except ImportError: # CRUFT: python 2 support 
    1416    import thread 
    15  
    16 if sys.platform.count("darwin") > 0: 
    17     import time 
    18     stime = time.time() 
    19  
    20     def clock(): 
    21         return time.time() - stime 
    22  
    23     def sleep(t): 
    24         return time.sleep(t) 
    25 else: 
    26     from time import clock 
    27     from time import sleep 
     17try: 
     18    from time import perf_counter as clock 
     19except ImportError: # CRUFT: python < 3.3 
     20    if sys.platform.count("darwin") > 0: 
     21        from time import time as clock 
     22    else: 
     23        from time import clock 
    2824 
    2925logger = logging.getLogger(__name__) 
    30  
    3126 
    3227class CalcThread: 
     
    248243                self.exception_handler(*sys.exc_info()) 
    249244                return 
    250             except Exception: 
     245            except Exception as exc: 
    251246                pass 
    252247        logger.error(traceback.format_exc()) 
  • src/sas/sascalc/data_util/ordereddicttest.py

    rb699768 r44a698c  
    147147                    ]): 
    148148            self.assert_(dup is not od) 
    149             self.assertEquals(dup, od) 
    150             self.assertEquals(list(dup.items()), list(od.items())) 
    151             self.assertEquals(len(dup), len(od)) 
    152             self.assertEquals(type(dup), type(od)) 
     149            self.assertEqual(dup, od) 
     150            self.assertEqual(list(dup.items()), list(od.items())) 
     151            self.assertEqual(len(dup), len(od)) 
     152            self.assertEqual(type(dup), type(od)) 
    153153 
    154154    def test_repr(self): 
  • src/sas/sascalc/dataloader/loader.py

    r8db20a9 r44a698c  
    169169                        if self._identify_plugin(module): 
    170170                            readers_found += 1 
    171                     except: 
     171                    except Exception as exc: 
    172172                        msg = "Loader: Error importing " 
    173                         msg += "%s\n  %s" % (item, sys.exc_value) 
     173                        msg += "%s\n  %s" % (item, exc) 
    174174                        logger.error(msg) 
    175175 
     
    191191                                if self._identify_plugin(module): 
    192192                                    readers_found += 1 
    193                             except: 
     193                            except Exception as exc: 
    194194                                msg = "Loader: Error importing" 
    195                                 msg += " %s\n  %s" % (mfile, sys.exc_value) 
     195                                msg += " %s\n  %s" % (mfile, exc) 
    196196                                logger.error(msg) 
    197197 
    198                     except: 
     198                    except Exception as exc: 
    199199                        msg = "Loader: Error importing " 
    200                         msg += " %s\n  %s" % (item, sys.exc_value) 
     200                        msg += " %s\n  %s" % (item, exc) 
    201201                        logger.error(msg) 
    202202 
     
    242242                    self.writers[ext].append(loader.write) 
    243243 
    244             except: 
     244            except Exception as exc: 
    245245                msg = "Loader: Error accessing" 
    246                 msg += " Reader in %s\n  %s" % (module.__name__, sys.exc_value) 
     246                msg += " Reader in %s\n  %s" % (module.__name__, exc) 
    247247                logger.error(msg) 
    248248        return reader_found 
     
    275275                    self.wildcards.append(wcard) 
    276276 
    277         except: 
     277        except Exception as exc: 
    278278            msg = "Loader: Error accessing Reader " 
    279             msg += "in %s\n  %s" % (loader.__name__, sys.exc_value) 
     279            msg += "in %s\n  %s" % (loader.__name__, exc) 
    280280            logger.error(msg) 
    281281        return reader_found 
     
    320320                        self.writers[ext].insert(0, loader.write) 
    321321 
    322             except: 
     322            except Exception as exc: 
    323323                msg = "Loader: Error accessing Reader" 
    324                 msg += " in %s\n  %s" % (module.__name__, sys.exc_value) 
     324                msg += " in %s\n  %s" % (module.__name__, exc) 
    325325                logger.error(msg) 
    326326        return reader_found 
  • src/sas/sascalc/dataloader/manipulations.py

    r574adc7 r44a698c  
    928928 
    929929        # Organize the results 
    930         for i in range(self.nbins): 
    931             y[i] = y[i] / y_counts[i] 
    932             y_err[i] = math.sqrt(y_err[i]) / y_counts[i] 
    933  
    934             # The type of averaging: phi,q2, or q 
    935             # Calculate x[i]should be at the center of the bin 
     930        with np.errstate(divide='ignore', invalid='ignore'): 
     931            y = y/y_counts 
     932            y_err = np.sqrt(y_err)/y_counts 
     933            # The type of averaging: phi, q2, or q 
     934            # Calculate x values at the center of the bin 
    936935            if run.lower() == 'phi': 
    937                 x[i] = (self.phi_max - self.phi_min) / self.nbins * \ 
    938                     (1.0 * i + 0.5) + self.phi_min 
     936                step = (self.phi_max - self.phi_min) / self.nbins 
     937                x = (np.arange(self.nbins) + 0.5) * step + self.phi_min 
    939938            else: 
    940                 # We take the center of ring area, not radius. 
    941                 # This is more accurate than taking the radial center of ring. 
    942                 # delta_r = (self.r_max - self.r_min) / self.nbins 
    943                 # r_inner = self.r_min + delta_r * i 
    944                 # r_outer = r_inner + delta_r 
    945                 # x[i] = math.sqrt((r_inner * r_inner + r_outer * r_outer) / 2) 
    946                 x[i] = x[i] / y_counts[i] 
    947         y_err[y_err == 0] = np.average(y_err) 
     939                # set q to the average of the q values within each bin 
     940                x = x/y_counts 
     941 
     942                ### Alternate algorithm 
     943                ## We take the center of ring area, not radius. 
     944                ## This is more accurate than taking the radial center of ring. 
     945                #step = (self.r_max - self.r_min) / self.nbins 
     946                #r_inner = self.r_min + step * np.arange(self.nbins) 
     947                #x = math.sqrt((r_inner**2 + (r_inner + step)**2) / 2) 
     948 
    948949        idx = (np.isfinite(y) & np.isfinite(y_err)) 
    949950        if x_err is not None: 
  • src/sas/sascalc/dataloader/readers/associations.py

    r8db20a9 r44a698c  
    5454                exec("loader.associate_file_type('%s', %s)" 
    5555                     % (ext.upper(), reader)) 
    56             except: 
     56            except Exception as exc: 
    5757                msg = "read_associations: skipping association" 
    58                 msg += " for %s\n  %s" % (ext.lower(), sys.exc_value) 
     58                msg += " for %s\n  %s" % (ext.lower(), exc) 
    5959                logger.error(msg) 
  • src/sas/sascalc/fit/expression.py

    re4c475b7 r44a698c  
    188188 
    189189    # Initialize dictionary with available functions 
    190     globals = {} 
    191     globals.update(math.__dict__) 
    192     globals.update(dict(arcsin=math.asin,arccos=math.acos, 
     190    global_context = {} 
     191    global_context.update(math.__dict__) 
     192    global_context.update(dict(arcsin=math.asin,arccos=math.acos, 
    193193                        arctan=math.atan,arctan2=math.atan2)) 
    194     globals.update(context) 
    195     globals.update(parameters) 
    196     globals['id'] = id 
    197     locals = {} 
     194    global_context.update(context) 
     195    global_context.update(parameters) 
     196    global_context['id'] = id 
     197    local_context = {} 
    198198 
    199199    # Define the constraints function 
     
    210210 
    211211    #print("Function: "+functiondef) 
    212     # Python 2.7 
    213     #exec (functiondef in globals,locals) 
    214     # Python 3.5 
    215     exec (functiondef, globals, locals) 
    216  
    217     retfn = locals['eval_expressions'] 
     212    # CRUFT: python < 3.0;  doc builder isn't allowing the following exec 
     213    # https://stackoverflow.com/questions/4484872/why-doesnt-exec-work-in-a-function-with-a-subfunction/41368813#comment73790496_41368813 
     214    #exec(functiondef, global_context, local_context) 
     215    eval(compile(functiondef, '<string>', 'exec'), global_context, local_context) 
     216    retfn = local_context['eval_expressions'] 
    218217 
    219218    # Remove garbage added to globals by exec 
    220     globals.pop('__doc__',None) 
    221     globals.pop('__name__',None) 
    222     globals.pop('__file__',None) 
    223     globals.pop('__builtins__') 
     219    global_context.pop('__doc__', None) 
     220    global_context.pop('__name__', None) 
     221    global_context.pop('__file__', None) 
     222    global_context.pop('__builtins__') 
    224223    #print globals.keys() 
    225224 
     
    236235 
    237236    # Break pairs into left set and right set 
    238     left,right = [set(s) for s in zip(*pairs)] if pairs != [] else ([],[]) 
    239     while pairs != []: 
     237    # Note: pairs is array or list, so use "len(pairs) > 0" to check for empty. 
     238    left,right = [set(s) for s in zip(*pairs)] if len(pairs) > 0 else ([],[]) 
     239    while len(pairs) > 0: 
    240240        #print "within",pairs 
    241241        # Find which items only occur on the right 
     
    265265    satisfies the partial ordering given by the pairs in partial order. 
    266266    """ 
    267     left,right = zip(*pairs) if pairs != [] else ([],[]) 
     267    # Note: pairs is array or list, so use "len(pairs) > 0" to check for empty. 
     268    left,right = zip(*pairs) if len(pairs) > 0 else ([],[]) 
    268269    items = set(left) 
    269270    n = order_dependencies(pairs) 
  • src/sas/sascalc/fit/pagestate.py

    rb1b71ad r44a698c  
    640640                if len(value.strip()) == 0: 
    641641                    continue 
    642                 title = value + " [" + repo_time + "]" 
     642                title = (value + " [" + repo_time + "] [SasView v" + 
     643                         SASVIEW_VERSION + "]") 
    643644                title_name = HEADER % title 
    644645            elif name == "data": 
     
    649650                    #Truncating string so print doesn't complain of being outside margins 
    650651                    if sys.platform != "win32": 
    651                         MAX_STRING_LENGHT = 50 
    652                         if len(file_value) > MAX_STRING_LENGHT: 
    653                             file_value = "File name:.."+file_value[-MAX_STRING_LENGHT+10:] 
     652                        MAX_STRING_LENGTH = 50 
     653                        if len(file_value) > MAX_STRING_LENGTH: 
     654                            file_value = "File name:.."+file_value[-MAX_STRING_LENGTH+10:] 
    654655                    file_name = CENTRE % file_value 
    655656                    if len(title) == 0: 
     
    904905                doc_model = newdoc.createElement('model_list_item') 
    905906                doc_model.setAttribute('checked', str(model[0].GetValue())) 
    906                 keys = model[1].keys() 
     907                keys = list(model[1].keys()) 
    907908                doc_model.setAttribute('name', str(keys[0])) 
    908909                values = model[1].get(keys[0]) 
     
    963964        if node.get('version'): 
    964965            # Get the version for model conversion purposes 
    965             x = re.sub('[^\d.]', '', node.get('version')) 
     966            x = re.sub(r'[^\d.]', '', node.get('version')) 
    966967            self.version = tuple(int(e) for e in str.split(x, ".")) 
    967968            # The tuple must be at least 3 items long 
     
    983984                try: 
    984985                    self.timestamp = float(entry.get('epoch')) 
    985                 except Exception: 
     986                except Exception as exc: 
    986987                    msg = "PageState.fromXML: Could not" 
    987                     msg += " read timestamp\n %s" % sys.exc_value 
     988                    msg += " read timestamp\n %s" % exc 
    988989                    logger.error(msg) 
    989990 
  • src/sas/sascalc/pr/distance_explorer.py

    r959eb01 r44a698c  
    9999                results.pos_err.append(pos_err) 
    100100                results.osc.append(osc) 
    101             except: 
     101            except Exception as exc: 
    102102                # This inversion failed, skip this D_max value 
    103103                msg = "ExploreDialog: inversion failed for " 
    104                 msg += "D_max=%s\n %s" % (str(d), sys.exc_value) 
     104                msg += "D_max=%s\n %s" % (str(d), exc) 
    105105                results.errors.append(msg) 
    106106 
  • src/sas/sascalc/pr/num_term.py

    r57a91fc r44a698c  
    182182                data_y = np.append(data_y, test_y) 
    183183                data_err = np.append(data_err, err) 
    184             except: 
    185                 logger.error(sys.exc_value) 
     184            except Exception as exc: 
     185                logger.error(exc) 
    186186 
    187187    return data_x, data_y, data_err 
  • src/sas/sascalc/realspace/VolumeCanvas.py

    r98e3f24 r44a698c  
    472472            Return a list of the shapes 
    473473        """ 
    474         return self.shapes.keys() 
     474        return list(self.shapes.keys()) 
    475475 
    476476    def _addSingleShape(self, shapeDesc): 
Note: See TracChangeset for help on using the changeset viewer.