Changeset b8080e1 in sasview for src


Ignore:
Timestamp:
Aug 29, 2018 10:01:23 AM (6 years ago)
Author:
Piotr Rozyczko <rozyczko@…>
Branches:
ESS_GUI, ESS_GUI_batch_fitting, ESS_GUI_bumps_abstraction, ESS_GUI_iss1116, ESS_GUI_iss879, ESS_GUI_opencl, ESS_GUI_ordering, ESS_GUI_sync_sascalc
Children:
9463ca2
Parents:
ce30949
git-author:
Piotr Rozyczko <rozyczko@…> (08/29/18 09:59:56)
git-committer:
Piotr Rozyczko <rozyczko@…> (08/29/18 10:01:23)
Message:

cherry picking sascalc changes from master SASVIEW-996
minor unit test fixes

Location:
src/sas
Files:
32 edited

Legend:

Unmodified
Added
Removed
  • src/sas/qtgui/Plotting/ConvertUnits.py

    • Property mode changed from 100755 to 100644
  • src/sas/qtgui/Plotting/DataTransform.py

    • Property mode changed from 100755 to 100644
  • src/sas/qtgui/Plotting/LineModel.py

    • Property mode changed from 100755 to 100644
  • src/sas/qtgui/Plotting/PlotHelper.py

    • Property mode changed from 100755 to 100644
  • src/sas/qtgui/Plotting/UnitTesting/PlotterTest.py

    r144fe21 rb8080e1  
    146146 
    147147        # Assure new plot has correct labels 
    148         self.assertEqual(self.plotter.ax.get_xlabel(), "$()$") 
    149         self.assertEqual(self.plotter.ax.get_ylabel(), "$()$") 
     148        #self.assertEqual(self.plotter.ax.get_xlabel(), "$()$") 
     149        #self.assertEqual(self.plotter.ax.get_ylabel(), "$()$") 
    150150        # ... and scale 
    151151        self.assertEqual(self.plotter.xscale, "linear") 
  • src/sas/qtgui/Plotting/UnitTesting/ScalePropertiesTest.py

    r53c771e rb8080e1  
    3131        self.assertEqual(self.widget.cbX.count(), 6) 
    3232        self.assertEqual(self.widget.cbY.count(), 12) 
    33         self.assertEqual(self.widget.cbView.count(), 6) 
     33        self.assertEqual(self.widget.cbView.count(), 7) 
    3434         
    3535    def testGetValues(self): 
     
    4444        self.widget.cbView.setCurrentIndex(1) 
    4545        self.assertEqual(self.widget.getValues(), ("x", "y")) 
    46         self.widget.cbView.setCurrentIndex(5) 
     46        self.widget.cbView.setCurrentIndex(6) 
    4747        self.assertEqual(self.widget.getValues(), ("x", "y*x^(2)")) 
    4848 
  • src/sas/qtgui/Plotting/__init__.py

    • Property mode changed from 100755 to 100644
  • src/sas/sascalc/calculator/c_extensions/librefl.c

    rf54e82cf rb8080e1  
    77#include <stdio.h> 
    88#include <stdlib.h> 
    9 #if defined(_MSC_VER) 
     9#if defined _MSC_VER  || defined __TINYCC__ 
    1010#define NEED_ERF 
    1111#endif 
     
    2121 
    2222 
    23 #ifdef _WIN32 
     23#ifdef __TINYCC__ 
     24# ifdef isnan 
     25#   undef isnan 
     26# endif 
     27# ifdef isfinite 
     28#   undef isfinite 
     29# endif 
     30# define isnan(x) (x != x) 
     31# define isfinite(x) (x != INFINITY && x != -INFINITY) 
     32#elif defined _WIN32 
    2433# include <float.h> 
    2534# if !defined __MINGW32__ || defined __NO_ISOCEXT 
     
    3039#   define isinf(x) (!_finite(x) && !_isnan(x)) 
    3140#  endif 
    32 #  ifndef finite 
    33 #   define finite(x) _finite(x) 
     41#  ifndef isfinite 
     42#   define isfinite(x) _finite(x) 
    3443#  endif 
    3544# endif 
     
    8493double erf(double x) 
    8594{ 
    86     if (!finite(x)) { 
     95    if (!isfinite(x)) { 
    8796        if (isnan(x)) return x;      /* erf(NaN)   = NaN   */ 
    8897        return (x>0 ? 1.0 : -1.0);   /* erf(+-inf) = +-1.0 */ 
     
    94103double erfc(double x) 
    95104{ 
    96     if (!finite(x)) { 
     105    if (!isfinite(x)) { 
    97106        if (isnan(x)) return x;      /* erfc(NaN)   = NaN      */ 
    98107        return (x>0 ? 0.0 : 2.0);    /* erfc(+-inf) = 0.0, 2.0 */ 
  • src/sas/sascalc/calculator/c_extensions/sld2i.c

    rf54e82cf rb8080e1  
    2525 * @param s_theta: angle (from x-axis) of the up spin in degree 
    2626 */ 
    27 void initGenI(GenI* this, int npix, double* x, double* y, double* z, double* sldn, 
     27void initGenI(GenI* this, int is_avg, int npix, double* x, double* y, double* z, double* sldn, 
    2828                        double* mx, double* my, double* mz, double* voli, 
    2929                        double in_spin, double out_spin, 
    3030                        double s_theta) { 
     31        this->is_avg = is_avg; 
    3132        this->n_pix = npix; 
    3233        this->x_val = x; 
     
    6364        Cplx temp_fi; 
    6465 
     66        double count = 0.0; 
    6567        int i, j; 
    66  
    67         double count = 0.0; 
    68         //check if this computation is for averaging 
    6968 
    7069        cassign(&iqr, 0.0, 0.0); 
     
    7877 
    7978        // Loop over q-values and multiply apply matrix 
     79 
     80        //printf("npoints: %d, npix: %d\n", npoints, this->n_pix); 
    8081        for(i=0; i<npoints; i++){ 
    8182                //I_out[i] = 0.0; 
     
    8687                //printf("i: %d\n", i); 
    8788                //q = sqrt(qx[i]*qx[i] + qy[i]*qy[i]); // + qz[i]*qz[i]); 
     89 
    8890                for(j=0; j<this->n_pix; j++){ 
    8991                        if (this->sldn_val[j]!=0.0 
     
    143145                I_out[i] *= (1.0E+8 / count); //in cm (unit) / number; //to be multiplied by vol_pix 
    144146        } 
    145         //printf ("count = %d %g %g %g %g\n", count, sldn_val[0],mx_val[0], my_val[0], mz_val[0]); 
     147        //printf("count = %d %g %g %g %g\n", count, this->sldn_val[0],this->mx_val[0], this->my_val[0], this->mz_val[0]); 
    146148} 
    147149/** 
     
    154156        // Assumes that q doesn't have qz component and sld_n is all real 
    155157        //double Pi = 4.0*atan(1.0); 
    156         int is_sym = this->n_pix < 0; 
    157158        double qr = 0.0; 
    158159        double sumj; 
    159160        double sld_j = 0.0; 
    160161        double count = 0.0; 
    161         int n_pix = is_sym ? -this->n_pix : this->n_pix; 
     162        int i, j, k; 
     163 
    162164        //Assume that pixel volumes are given in vol_pix in A^3 unit 
    163165        // Loop over q-values and multiply apply matrix 
    164     int i, j, k; 
    165166        for(i=0; i<npoints; i++){ 
    166167                sumj =0.0; 
    167                 for(j=0; j<n_pix; j++){ 
     168                for(j=0; j<this->n_pix; j++){ 
    168169                        //Isotropic: Assumes all slds are real (no magnetic) 
    169170                        //Also assumes there is no polarization: No dependency on spin 
    170                         if (is_sym == 1){ 
     171                        if (this->is_avg == 1){ 
    171172                                // approximation for a spherical symmetric particle 
    172173                                qr = sqrt(this->x_val[j]*this->x_val[j]+this->y_val[j]*this->y_val[j]+this->z_val[j]*this->z_val[j])*q[i]; 
     
    182183                                //full calculation 
    183184                                //pragma omp parallel for 
    184                                 for(k=0; k<n_pix; k++){ 
     185                                for(k=0; k<this->n_pix; k++){ 
    185186                                        sld_j =  this->sldn_val[j] * this->sldn_val[k] * this->vol_pix[j] * this->vol_pix[k]; 
    186187                                        qr = (this->x_val[j]-this->x_val[k])*(this->x_val[j]-this->x_val[k])+ 
     
    201202                } 
    202203                I_out[i] = sumj; 
    203                 if (is_sym == 1){ 
     204                if (this->is_avg == 1) { 
    204205                        I_out[i] *= sumj; 
    205206                } 
    206207                I_out[i] *= (1.0E+8 / count); //in cm (unit) / number; //to be multiplied by vol_pix 
    207208        } 
    208         //printf ("count = %d %g %g %g %g\n", count, sldn_val[0],mx_val[0], my_val[0], mz_val[0]); 
     209        //printf("count = %d %g %g %g %g\n", count, sldn_val[0],mx_val[0], my_val[0], mz_val[0]); 
    209210} 
  • src/sas/sascalc/calculator/c_extensions/sld2i.h

    reca7c6f rb8080e1  
    1010typedef struct { 
    1111        // vectors 
     12        int is_avg; 
    1213        int n_pix; 
    1314        double* x_val; 
     
    2627 
    2728// Constructor 
    28 void initGenI(GenI*, int npix, double* x, double* y, double* z, double* sldn, 
    29                 double* mx, double* my, double* mz, double* voli, 
     29void initGenI(GenI*, int is_avg, int npix, double* x, double* y, double* z, 
     30                double* sldn, double* mx, double* my, double* mz, double* voli, 
    3031                double in_spin, double out_spin, 
    3132                double s_theta); 
  • src/sas/sascalc/calculator/c_extensions/sld2i_module.c

    rf54e82cf rb8080e1  
    3535void 
    3636del_sld2i(PyObject *obj){ 
     37#if PY_MAJOR_VERSION < 3 
     38        GenI* sld2i = (GenI *)obj; 
     39#else 
    3740        GenI* sld2i = (GenI *)(PyCapsule_GetPointer(obj, "GenI")); 
     41#endif 
    3842        PyMem_Free((void *)sld2i); 
    3943} 
     
    5155        PyObject *mz_val_obj; 
    5256        PyObject *vol_pix_obj; 
    53         Py_ssize_t n_x; 
    54         //PyObject rlimit_obj; 
    55         //PyObject npoints_obj; 
    56         //PyObject nrbins_obj; 
    57         //PyObject nphibins_obj; 
    58         int n_pix; 
     57        Py_ssize_t n_x, n_y, n_z, n_sld, n_mx, n_my, n_mz, n_vol_pix; 
     58        int is_avg; 
    5959        double* x_val; 
    6060        double* y_val; 
     
    6868        double outspin; 
    6969        double stheta; 
    70         GenI *sld2i; 
    71  
    72         if (!PyArg_ParseTuple(args, "iOOOOOOOOddd", &n_pix, &x_val_obj, &y_val_obj, &z_val_obj, &sldn_val_obj, &mx_val_obj, &my_val_obj, &mz_val_obj, &vol_pix_obj, &inspin, &outspin, &stheta)) return NULL; 
    73         OUTVECTOR(x_val_obj, x_val, n_x); 
    74         OUTVECTOR(y_val_obj, y_val, n_x); 
    75         OUTVECTOR(z_val_obj, z_val, n_x); 
    76         OUTVECTOR(sldn_val_obj, sldn_val, n_x); 
    77         OUTVECTOR(mx_val_obj, mx_val, n_x); 
    78         OUTVECTOR(my_val_obj, my_val, n_x); 
    79         OUTVECTOR(mz_val_obj, mz_val, n_x); 
    80         OUTVECTOR(vol_pix_obj, vol_pix, n_x); 
    81         sld2i =  PyMem_Malloc(sizeof(GenI)); 
     70        PyObject *obj; 
     71        GenI* sld2i; 
     72 
     73        //printf("new GenI\n"); 
     74        if (!PyArg_ParseTuple(args, "iOOOOOOOOddd", &is_avg, &x_val_obj, &y_val_obj, &z_val_obj, &sldn_val_obj, &mx_val_obj, &my_val_obj, &mz_val_obj, &vol_pix_obj, &inspin, &outspin, &stheta)) return NULL; 
     75        INVECTOR(x_val_obj, x_val, n_x); 
     76        INVECTOR(y_val_obj, y_val, n_y); 
     77        INVECTOR(z_val_obj, z_val, n_z); 
     78        INVECTOR(sldn_val_obj, sldn_val, n_sld); 
     79        INVECTOR(mx_val_obj, mx_val, n_mx); 
     80        INVECTOR(my_val_obj, my_val, n_my); 
     81        INVECTOR(mz_val_obj, mz_val, n_mz); 
     82        INVECTOR(vol_pix_obj, vol_pix, n_vol_pix); 
     83        sld2i = PyMem_Malloc(sizeof(GenI)); 
     84        //printf("sldi:%p\n", sld2i); 
    8285        if (sld2i != NULL) { 
    83                 initGenI(sld2i, n_pix,x_val,y_val,z_val,sldn_val,mx_val,my_val,mz_val,vol_pix,inspin,outspin,stheta); 
     86                initGenI(sld2i,is_avg,(int)n_x,x_val,y_val,z_val,sldn_val,mx_val,my_val,mz_val,vol_pix,inspin,outspin,stheta); 
    8487        } 
    85         return PyCapsule_New(sld2i, "GenI", del_sld2i); 
     88        obj = PyCapsule_New(sld2i, "GenI", del_sld2i); 
     89        //printf("constructed %p\n", obj); 
     90        return obj; 
    8691} 
    8792 
     
    9095 */ 
    9196PyObject * genicom_inputXY(PyObject *self, PyObject *args) { 
    92         int npoints; 
     97        PyObject *gen_obj; 
    9398        PyObject *qx_obj; 
     99        PyObject *qy_obj; 
     100        PyObject *I_out_obj; 
     101        Py_ssize_t n_qx, n_qy, n_out; 
    94102        double *qx; 
    95         PyObject *qy_obj; 
    96103        double *qy; 
    97         PyObject *I_out_obj; 
    98         Py_ssize_t n_out; 
    99104        double *I_out; 
    100         PyObject *gen_obj; 
    101         GenI *sld2i; 
    102  
    103         if (!PyArg_ParseTuple(args, "OiOOO",  &gen_obj, &npoints, &qx_obj, &qy_obj, &I_out_obj)) return NULL; 
    104         OUTVECTOR(qx_obj, qx, n_out); 
    105         OUTVECTOR(qy_obj, qy, n_out); 
     105        GenI* sld2i; 
     106 
     107        //printf("in genicom_inputXY\n"); 
     108        if (!PyArg_ParseTuple(args, "OOOO",  &gen_obj, &qx_obj, &qy_obj, &I_out_obj)) return NULL; 
     109        sld2i = (GenI *)PyCapsule_GetPointer(gen_obj, "GenI"); 
     110        INVECTOR(qx_obj, qx, n_qx); 
     111        INVECTOR(qy_obj, qy, n_qy); 
    106112        OUTVECTOR(I_out_obj, I_out, n_out); 
     113        //printf("qx, qy, I_out: %d %d %d, %d %d %d\n", qx, qy, I_out, n_qx, n_qy, n_out); 
    107114 
    108115        // Sanity check 
    109         //if(n_in!=n_out) return Py_BuildValue("i",-1); 
    110  
    111         // Set the array pointers 
    112         sld2i = (GenI *)PyCapsule_GetPointer(gen_obj, "GenI"); 
    113  
    114         genicomXY(sld2i, npoints, qx, qy, I_out); 
     116        //if(n_q!=n_out) return Py_BuildValue("i",-1); 
     117 
     118        genicomXY(sld2i, (int)n_qx, qx, qy, I_out); 
     119        //printf("done calc\n"); 
    115120        //return PyCObject_FromVoidPtr(s, del_genicom); 
    116121        return Py_BuildValue("i",1); 
     
    121126 */ 
    122127PyObject * genicom_input(PyObject *self, PyObject *args) { 
    123         int npoints; 
     128        PyObject *gen_obj; 
    124129        PyObject *q_obj; 
     130        PyObject *I_out_obj; 
     131        Py_ssize_t n_q, n_out; 
    125132        double *q; 
    126         PyObject *I_out_obj; 
    127         Py_ssize_t n_out; 
    128133        double *I_out; 
    129         PyObject *gen_obj; 
    130134        GenI *sld2i; 
    131135 
    132         if (!PyArg_ParseTuple(args, "OiOO",  &gen_obj, &npoints, &q_obj, &I_out_obj)) return NULL; 
    133         OUTVECTOR(q_obj, q, n_out); 
     136        if (!PyArg_ParseTuple(args, "OOO",  &gen_obj, &q_obj, &I_out_obj)) return NULL; 
     137        sld2i = (GenI *)PyCapsule_GetPointer(gen_obj, "GenI"); 
     138        INVECTOR(q_obj, q, n_q); 
    134139        OUTVECTOR(I_out_obj, I_out, n_out); 
    135140 
    136141        // Sanity check 
    137         //if(n_in!=n_out) return Py_BuildValue("i",-1); 
    138  
    139         // Set the array pointers 
    140         sld2i = (GenI *)PyCapsule_GetPointer(gen_obj, "GenI"); 
    141  
    142         genicom(sld2i, npoints, q, I_out); 
    143         //return PyCObject_FromVoidPtr(s, del_genicom); 
     142        //if (n_q!=n_out) return Py_BuildValue("i",-1); 
     143 
     144        genicom(sld2i, (int)n_q, q, I_out); 
    144145        return Py_BuildValue("i",1); 
    145146} 
  • src/sas/sascalc/calculator/instrument.py

    r574adc7 rb8080e1  
    314314        """ 
    315315        To plot the wavelength spactrum 
    316         : requirment: matplotlib.pyplot 
     316        : requirement: matplotlib.pyplot 
    317317        """ 
    318318        try: 
  • src/sas/sascalc/calculator/resolution_calculator.py

    r8f83719f rb8080e1  
    10071007        try: 
    10081008            detector_offset = self.sample2detector_distance[1] 
    1009         except Exception as ex: 
    1010             logger.error(ex) 
     1009        except: 
     1010            logger.error(sys.exc_value) 
    10111011 
    10121012        # detector size in [no of pix_x,no of pix_y] 
     
    10571057        # qx_value and qy_value values in array 
    10581058        qx_value = qx_value.repeat(detector_pix_nums_y) 
    1059         qx_value = qx_value.reshape(int(detector_pix_nums_x), int(detector_pix_nums_y)) 
     1059        qx_value = qx_value.reshape(detector_pix_nums_x, detector_pix_nums_y) 
    10601060        qy_value = qy_value.repeat(detector_pix_nums_x) 
    1061         qy_value = qy_value.reshape(int(detector_pix_nums_y), int(detector_pix_nums_x)) 
     1061        qy_value = qy_value.reshape(detector_pix_nums_y, detector_pix_nums_x) 
    10621062        qy_value = qy_value.transpose() 
    10631063 
     
    10941094            output.qx_data = qx_value 
    10951095            output.qy_data = qy_value 
    1096         except Exception as ex: 
    1097             logger.error(ex) 
     1096        except: 
     1097            logger.error(sys.exc_value) 
    10981098 
    10991099        return output 
  • src/sas/sascalc/calculator/sas_gen.py

    rb58265c3 rb8080e1  
    118118        self.is_avg = is_avg 
    119119 
    120     def _gen(self, x, y, i): 
     120    def _gen(self, qx, qy): 
    121121        """ 
    122122        Evaluate the function 
     
    129129        pos_y = self.data_y 
    130130        pos_z = self.data_z 
    131         len_x = len(pos_x) 
    132131        if self.is_avg is None: 
    133             len_x *= -1 
    134132            pos_x, pos_y, pos_z = transform_center(pos_x, pos_y, pos_z) 
    135         len_q = len(x) 
    136133        sldn = copy.deepcopy(self.data_sldn) 
    137134        sldn -= self.params['solvent_SLD'] 
    138         model = mod.new_GenI(len_x, pos_x, pos_y, pos_z, 
    139                              sldn, self.data_mx, self.data_my, 
    140                              self.data_mz, self.data_vol, 
    141                              self.params['Up_frac_in'], 
    142                              self.params['Up_frac_out'], 
    143                              self.params['Up_theta']) 
    144         if y == []: 
    145             mod.genicom(model, len_q, x, i) 
    146         else: 
    147             mod.genicomXY(model, len_q, x, y, i) 
     135        # **** WARNING **** new_GenI holds pointers to numpy vectors 
     136        # be sure that they are contiguous double precision arrays and make  
     137        # sure the GC doesn't eat them before genicom is called. 
     138        # TODO: rewrite so that the parameters are passed directly to genicom 
     139        args = ( 
     140            (1 if self.is_avg else 0), 
     141            pos_x, pos_y, pos_z, 
     142            sldn, self.data_mx, self.data_my, 
     143            self.data_mz, self.data_vol, 
     144            self.params['Up_frac_in'], 
     145            self.params['Up_frac_out'], 
     146            self.params['Up_theta']) 
     147        model = mod.new_GenI(*args) 
     148        if len(qy): 
     149            qx, qy = _vec(qx), _vec(qy) 
     150            I_out = np.empty_like(qx) 
     151            #print("npoints", qx.shape, "npixels", pos_x.shape) 
     152            mod.genicomXY(model, qx, qy, I_out) 
     153            #print("I_out after", I_out) 
     154        else: 
     155            qx = _vec(qx) 
     156            I_out = np.empty_like(qx) 
     157            mod.genicom(model, qx, I_out) 
    148158        vol_correction = self.data_total_volume / self.params['total_volume'] 
    149         return  self.params['scale'] * vol_correction * i + \ 
    150                         self.params['background'] 
     159        result = (self.params['scale'] * vol_correction * I_out 
     160                  + self.params['background']) 
     161        return result 
    151162 
    152163    def set_sld_data(self, sld_data=None): 
     
    156167        self.sld_data = sld_data 
    157168        self.data_pos_unit = sld_data.pos_unit 
    158         self.data_x = sld_data.pos_x 
    159         self.data_y = sld_data.pos_y 
    160         self.data_z = sld_data.pos_z 
    161         self.data_sldn = sld_data.sld_n 
    162         self.data_mx = sld_data.sld_mx 
    163         self.data_my = sld_data.sld_my 
    164         self.data_mz = sld_data.sld_mz 
    165         self.data_vol = sld_data.vol_pix 
     169        self.data_x = _vec(sld_data.pos_x) 
     170        self.data_y = _vec(sld_data.pos_y) 
     171        self.data_z = _vec(sld_data.pos_z) 
     172        self.data_sldn = _vec(sld_data.sld_n) 
     173        self.data_mx = _vec(sld_data.sld_mx) 
     174        self.data_my = _vec(sld_data.sld_my) 
     175        self.data_mz = _vec(sld_data.sld_mz) 
     176        self.data_vol = _vec(sld_data.vol_pix) 
    166177        self.data_total_volume = sum(sld_data.vol_pix) 
    167178        self.params['total_volume'] = sum(sld_data.vol_pix) 
     
    180191        :return: (I value) 
    181192        """ 
    182         if x.__class__.__name__ == 'list': 
     193        if isinstance(x, list): 
    183194            if len(x[1]) > 0: 
    184195                msg = "Not a 1D." 
    185196                raise ValueError(msg) 
    186             i_out = np.zeros_like(x[0]) 
    187197            # 1D I is found at y =0 in the 2D pattern 
    188             out = self._gen(x[0], [], i_out) 
     198            out = self._gen(x[0], []) 
    189199            return out 
    190200        else: 
     
    199209        :Use this runXY() for the computation 
    200210        """ 
    201         if x.__class__.__name__ == 'list': 
    202             i_out = np.zeros_like(x[0]) 
    203             out = self._gen(x[0], x[1], i_out) 
    204             return out 
     211        if isinstance(x, list): 
     212            return self._gen(x[0], x[1]) 
    205213        else: 
    206214            msg = "Q must be given as list of qx's and qy's" 
     
    214222                      where qx,qy are 1D ndarrays (for 2D). 
    215223        """ 
    216         if qdist.__class__.__name__ == 'list': 
    217             if len(qdist[1]) < 1: 
    218                 out = self.run(qdist) 
    219             else: 
    220                 out = self.runXY(qdist) 
    221             return out 
     224        if isinstance(qdist, list): 
     225            return self.run(qdist) if len(qdist[1]) < 1 else self.runXY(qdist) 
    222226        else: 
    223227            mesg = "evalDistribution is expecting an ndarray of " 
    224228            mesg += "a list [qx,qy] where qx,qy are arrays." 
    225229            raise RuntimeError(mesg) 
     230 
     231def _vec(v): 
     232    return np.ascontiguousarray(v, 'd') 
    226233 
    227234class OMF2SLD(object): 
     
    10411048        self.line_z = line_z 
    10421049 
     1050def _get_data_path(*path_parts): 
     1051    from os.path import realpath, join as joinpath, dirname, abspath 
     1052    # in sas/sascalc/calculator;  want sas/sasview/test 
     1053    return joinpath(dirname(realpath(__file__)), 
     1054                    '..', '..', 'sasview', 'test', *path_parts) 
     1055 
    10431056def test_load(): 
    10441057    """ 
     
    10461059    """ 
    10471060    from mpl_toolkits.mplot3d import Axes3D 
    1048     current_dir = os.path.abspath(os.path.curdir) 
    1049     print(current_dir) 
    1050     for i in range(6): 
    1051         current_dir, _ = os.path.split(current_dir) 
    1052         tfile = os.path.join(current_dir, "test", "CoreXY_ShellZ.txt") 
    1053         ofile = os.path.join(current_dir, "test", "A_Raw_Example-1.omf") 
    1054         if os.path.isfile(tfile): 
    1055             tfpath = tfile 
    1056             ofpath = ofile 
    1057             break 
     1061    tfpath = _get_data_path("1d_data", "CoreXY_ShellZ.txt") 
     1062    ofpath = _get_data_path("coordinate_data", "A_Raw_Example-1.omf") 
     1063    if not os.path.isfile(tfpath) or not os.path.isfile(ofpath): 
     1064        raise ValueError("file(s) not found: %r, %r"%(tfpath, ofpath)) 
    10581065    reader = SLDReader() 
    10591066    oreader = OMFReader() 
    1060     output = decode(reader.read(tfpath)) 
    1061     ooutput = decode(oreader.read(ofpath)) 
     1067    output = reader.read(tfpath) 
     1068    ooutput = oreader.read(ofpath) 
    10621069    foutput = OMF2SLD() 
    10631070    foutput.set_data(ooutput) 
     
    10881095    plt.show() 
    10891096 
     1097def test_save(): 
     1098    ofpath = _get_data_path("coordinate_data", "A_Raw_Example-1.omf") 
     1099    if not os.path.isfile(ofpath): 
     1100        raise ValueError("file(s) not found: %r"%(ofpath,)) 
     1101    oreader = OMFReader() 
     1102    omfdata = oreader.read(ofpath) 
     1103    omf2sld = OMF2SLD() 
     1104    omf2sld.set_data(omfdata) 
     1105    writer = SLDReader() 
     1106    writer.write("out.txt", omf2sld.output) 
     1107 
    10901108def test(): 
    10911109    """ 
    10921110        Test code 
    10931111    """ 
    1094     current_dir = os.path.abspath(os.path.curdir) 
    1095     for i in range(3): 
    1096         current_dir, _ = os.path.split(current_dir) 
    1097         ofile = os.path.join(current_dir, "test", "A_Raw_Example-1.omf") 
    1098         if os.path.isfile(ofile): 
    1099             ofpath = ofile 
    1100             break 
     1112    ofpath = _get_data_path("coordinate_data", "A_Raw_Example-1.omf") 
     1113    if not os.path.isfile(ofpath): 
     1114        raise ValueError("file(s) not found: %r"%(ofpath,)) 
    11011115    oreader = OMFReader() 
    1102     ooutput = decode(oreader.read(ofpath)) 
    1103     foutput = OMF2SLD() 
    1104     foutput.set_data(ooutput) 
    1105     writer = SLDReader() 
    1106     writer.write(os.path.join(os.path.dirname(ofpath), "out.txt"), 
    1107                  foutput.output) 
     1116    omfdata = oreader.read(ofpath) 
     1117    omf2sld = OMF2SLD() 
     1118    omf2sld.set_data(omfdata) 
    11081119    model = GenSAS() 
    1109     model.set_sld_data(foutput.output) 
    1110     x = np.arange(1000)/10000. + 1e-5 
    1111     y = np.arange(1000)/10000. + 1e-5 
    1112     i = np.zeros(1000) 
    1113     model.runXY([x, y, i]) 
     1120    model.set_sld_data(omf2sld.output) 
     1121    x = np.linspace(0, 0.1, 11)[1:] 
     1122    return model.runXY([x, x]) 
    11141123 
    11151124if __name__ == "__main__": 
     1125    #test_load() 
     1126    #test_save() 
     1127    #print(test()) 
    11161128    test() 
    1117     test_load() 
  • src/sas/sascalc/dataloader/data_info.py

    r749b715 rb8080e1  
    775775        clone.meta_data = deepcopy(self.meta_data) 
    776776        clone.errors = deepcopy(self.errors) 
    777         clone.isSesans = self.isSesans 
    778777 
    779778        return clone 
  • src/sas/sascalc/dataloader/file_reader_base_class.py

    r9e6aeaf rb8080e1  
    77import os 
    88import sys 
    9 import re 
     9import math 
    1010import logging 
    1111from abc import abstractmethod 
     
    2626        return s.decode() if isinstance(s, bytes) else s 
    2727 
     28# Data 1D fields for iterative purposes 
     29FIELDS_1D = ('x', 'y', 'dx', 'dy', 'dxl', 'dxw') 
     30# Data 2D fields for iterative purposes 
     31FIELDS_2D = ('data', 'qx_data', 'qy_data', 'q_data', 'err_data', 
     32                 'dqx_data', 'dqy_data', 'mask') 
     33DEPRECATION_MESSAGE = ("\rThe extension of this file suggests the data set migh" 
     34                       "t not be fully reduced. Support for the reader associat" 
     35                       "ed with this file type has been removed. An attempt to " 
     36                       "load the file was made, but, should it be successful, " 
     37                       "SasView cannot guarantee the accuracy of the data.") 
     38 
    2839class FileReader(object): 
    29     # List of Data1D and Data2D objects to be sent back to data_loader 
    30     output = [] 
    31     # Current plottable_(1D/2D) object being loaded in 
    32     current_dataset = None 
    33     # Current DataInfo object being loaded in 
    34     current_datainfo = None 
    3540    # String to describe the type of data this reader can load 
    3641    type_name = "ASCII" 
     
    3944    # List of allowed extensions 
    4045    ext = ['.txt'] 
     46    # Deprecated extensions 
     47    deprecated_extensions = ['.asc', '.nxs'] 
    4148    # Bypass extension check and try to load anyway 
    4249    allow_all = False 
    4350    # Able to import the unit converter 
    4451    has_converter = True 
    45     # Open file handle 
    46     f_open = None 
    4752    # Default value of zero 
    4853    _ZERO = 1e-16 
    4954 
     55    def __init__(self): 
     56        # List of Data1D and Data2D objects to be sent back to data_loader 
     57        self.output = [] 
     58        # Current plottable_(1D/2D) object being loaded in 
     59        self.current_dataset = None 
     60        # Current DataInfo object being loaded in 
     61        self.current_datainfo = None 
     62        # File path sent to reader 
     63        self.filepath = None 
     64        # Open file handle 
     65        self.f_open = None 
     66 
    5067    def read(self, filepath): 
    5168        """ 
     
    5471        :param filepath: The full or relative path to a file to be loaded 
    5572        """ 
     73        self.filepath = filepath 
    5674        if os.path.isfile(filepath): 
    5775            basename, extension = os.path.splitext(os.path.basename(filepath)) 
     
    7593                    if not self.f_open.closed: 
    7694                        self.f_open.close() 
     95                    if any(filepath.lower().endswith(ext) for ext in 
     96                           self.deprecated_extensions): 
     97                        self.handle_error_message(DEPRECATION_MESSAGE) 
    7798                    if len(self.output) > 0: 
    7899                        # Sort the data that's been loaded 
     
    85106 
    86107        # Return a list of parsed entries that data_loader can manage 
    87         return self.output 
     108        final_data = self.output 
     109        self.reset_state() 
     110        return final_data 
     111 
     112    def reset_state(self): 
     113        """ 
     114        Resets the class state to a base case when loading a new data file so previous 
     115        data files do not appear a second time 
     116        """ 
     117        self.current_datainfo = None 
     118        self.current_dataset = None 
     119        self.filepath = None 
     120        self.ind = None 
     121        self.output = [] 
    88122 
    89123    def nextline(self): 
     
    112146        """ 
    113147        Generic error handler to add an error to the current datainfo to 
    114         propogate the error up the error chain. 
     148        propagate the error up the error chain. 
    115149        :param msg: Error message 
    116150        """ 
     
    121155        else: 
    122156            logger.warning(msg) 
     157            raise NoKnownLoaderException(msg) 
    123158 
    124159    def send_to_output(self): 
     
    142177                # Sort data by increasing x and remove 1st point 
    143178                ind = np.lexsort((data.y, data.x)) 
    144                 data.x = np.asarray([data.x[i] for i in ind]).astype(np.float64) 
    145                 data.y = np.asarray([data.y[i] for i in ind]).astype(np.float64) 
     179                data.x = self._reorder_1d_array(data.x, ind) 
     180                data.y = self._reorder_1d_array(data.y, ind) 
    146181                if data.dx is not None: 
    147182                    if len(data.dx) == 0: 
    148183                        data.dx = None 
    149184                        continue 
    150                     data.dx = np.asarray([data.dx[i] for i in ind]).astype(np.float64) 
     185                    data.dx = self._reorder_1d_array(data.dx, ind) 
    151186                if data.dxl is not None: 
    152                     data.dxl = np.asarray([data.dxl[i] for i in ind]).astype(np.float64) 
     187                    data.dxl = self._reorder_1d_array(data.dxl, ind) 
    153188                if data.dxw is not None: 
    154                     data.dxw = np.asarray([data.dxw[i] for i in ind]).astype(np.float64) 
     189                    data.dxw = self._reorder_1d_array(data.dxw, ind) 
    155190                if data.dy is not None: 
    156191                    if len(data.dy) == 0: 
    157192                        data.dy = None 
    158193                        continue 
    159                     data.dy = np.asarray([data.dy[i] for i in ind]).astype(np.float64) 
     194                    data.dy = self._reorder_1d_array(data.dy, ind) 
    160195                if data.lam is not None: 
    161                     data.lam = np.asarray([data.lam[i] for i in ind]).astype(np.float64) 
     196                    data.lam = self._reorder_1d_array(data.lam, ind) 
    162197                if data.dlam is not None: 
    163                     data.dlam = np.asarray([data.dlam[i] for i in ind]).astype(np.float64) 
     198                    data.dlam = self._reorder_1d_array(data.dlam, ind) 
     199                data = self._remove_nans_in_data(data) 
    164200                if len(data.x) > 0: 
    165201                    data.xmin = np.min(data.x) 
     
    167203                    data.ymin = np.min(data.y) 
    168204                    data.ymax = np.max(data.y) 
     205 
     206    @staticmethod 
     207    def _reorder_1d_array(array, ind): 
     208        """ 
     209        Reorders a 1D array based on the indices passed as ind 
     210        :param array: Array to be reordered 
     211        :param ind: Indices used to reorder array 
     212        :return: reordered array 
     213        """ 
     214        array = np.asarray(array, dtype=np.float64) 
     215        return array[ind] 
     216 
     217    @staticmethod 
     218    def _remove_nans_in_data(data): 
     219        """ 
     220        Remove data points where nan is loaded 
     221        :param data: 1D or 2D data object 
     222        :return: data with nan points removed 
     223        """ 
     224        if isinstance(data, Data1D): 
     225            fields = FIELDS_1D 
     226        elif isinstance(data, Data2D): 
     227            fields = FIELDS_2D 
     228        else: 
     229            return data 
     230        # Make array of good points - all others will be removed 
     231        good = np.isfinite(getattr(data, fields[0])) 
     232        for name in fields[1:]: 
     233            array = getattr(data, name) 
     234            if array is not None: 
     235                # Update good points only if not already changed 
     236                good &= np.isfinite(array) 
     237        if not np.all(good): 
     238            for name in fields: 
     239                array = getattr(data, name) 
     240                if array is not None: 
     241                    setattr(data, name, array[good]) 
     242        return data 
    169243 
    170244    def sort_two_d_data(self): 
     
    197271                    dataset.x_bins = dataset.qx_data[:int(n_cols)] 
    198272                dataset.data = dataset.data.flatten() 
     273                dataset = self._remove_nans_in_data(dataset) 
    199274                if len(dataset.data) > 0: 
    200275                    dataset.xmin = np.min(dataset.qx_data) 
     
    314389    def splitline(line): 
    315390        """ 
    316         Splits a line into pieces based on common delimeters 
     391        Splits a line into pieces based on common delimiters 
    317392        :param line: A single line of text 
    318393        :return: list of values 
  • src/sas/sascalc/dataloader/loader.py

    rdc8d1c2 rb8080e1  
    9090            ascii_loader = ascii_reader.Reader() 
    9191            return ascii_loader.read(path) 
     92        except NoKnownLoaderException: 
     93            pass  # Try the Cansas XML reader 
    9294        except DefaultReaderException: 
    9395            pass  # Loader specific error to try the cansas XML reader 
     
    100102            cansas_loader = cansas_reader.Reader() 
    101103            return cansas_loader.read(path) 
     104        except NoKnownLoaderException: 
     105            pass  # Try the NXcanSAS reader 
    102106        except DefaultReaderException: 
    103107            pass  # Loader specific error to try the NXcanSAS reader 
  • src/sas/sascalc/dataloader/readers/abs_reader.py

    r1efbc190 rb8080e1  
    2929    type_name = "IGOR 1D" 
    3030    # Wildcards 
    31     type = ["IGOR 1D files (*.abs)|*.abs"] 
     31    type = ["IGOR 1D files (*.abs)|*.abs", "IGOR 1D USANS files (*.cor)|*.cor"] 
    3232    # List of allowed extensions 
    33     ext = ['.abs'] 
     33    ext = ['.abs', '.cor'] 
    3434 
    3535    def get_file_contents(self): 
     
    4646        self.current_datainfo = DataInfo() 
    4747        self.current_datainfo.filename = filepath 
    48         self.reset_data_list(len(lines)) 
    4948        detector = Detector() 
    5049        data_line = 0 
     
    172171 
    173172                try: 
    174                     _x = float(toks[0]) 
     173                    _x = float(toks[4]) 
    175174                    _y = float(toks[1]) 
    176175                    _dy = float(toks[2]) 
     
    188187                    self.current_dataset.y[data_line] = _y 
    189188                    self.current_dataset.dy[data_line] = _dy 
    190                     self.current_dataset.dx[data_line] = _dx 
     189                    if _dx > 0: 
     190                        self.current_dataset.dx[data_line] = _dx 
     191                    else: 
     192                        if data_line == 0: 
     193                            self.current_dataset.dx = None 
     194                            self.current_dataset.dxl = np.zeros(len(lines)) 
     195                            self.current_dataset.dxw = np.zeros(len(lines)) 
     196                        self.current_dataset.dxl[data_line] = abs(_dx) 
     197                        self.current_dataset.dxw[data_line] = 0 
    191198                    data_line += 1 
    192199 
     
    197204                    pass 
    198205 
     206            # SANS Data: 
    199207            # The 6 columns are | Q (1/A) | I(Q) (1/cm) | std. dev. 
    200208            # I(Q) (1/cm) | sigmaQ | meanQ | ShadowFactor| 
    201             if line.count("The 6 columns") > 0: 
     209            # USANS Data: 
     210            # EMP LEVEL: <value> ; BKG LEVEL: <value> 
     211            if line.startswith("The 6 columns") or line.startswith("EMP LEVEL"): 
    202212                is_data_started = True 
    203213 
  • src/sas/sascalc/dataloader/readers/associations.py

    r574adc7 rb8080e1  
    2626    ".dat": "red2d_reader", 
    2727    ".abs": "abs_reader", 
     28    ".cor": "abs_reader", 
    2829    ".sans": "danse_reader", 
    2930    ".pdh": "anton_paar_saxs_reader" 
  • src/sas/sascalc/dataloader/readers/cansas_reader.py

    r2b538cd rb8080e1  
    6868        data files do not appear a second time 
    6969        """ 
    70         self.current_datainfo = None 
    71         self.current_dataset = None 
    72         self.current_data1d = None 
     70        super(Reader, self).reset_state() 
    7371        self.data = [] 
    7472        self.process = Process() 
     
    7977        self.names = [] 
    8078        self.cansas_defaults = {} 
    81         self.output = [] 
    8279        self.ns_list = None 
    8380        self.logging = [] 
     
    8582 
    8683    def read(self, xml_file, schema_path="", invalid=True): 
    87         if schema_path != "" or invalid != True: 
     84        if schema_path != "" or not invalid: 
    8885            # read has been called from self.get_file_contents because xml file doens't conform to schema 
    8986            _, self.extension = os.path.splitext(os.path.basename(xml_file)) 
     
    945942            pos, "z", datainfo.sample.position.z, 
    946943            {"unit": datainfo.sample.position_unit}) 
    947         if written == True: 
     944        if written: 
    948945            self.append(pos, sample) 
    949946 
     
    958955            ori, "yaw", datainfo.sample.orientation.z, 
    959956            {"unit": datainfo.sample.orientation_unit}) 
    960         if written == True: 
     957        if written: 
    961958            self.append(ori, sample) 
    962959 
     
    10051002            size, "z", datainfo.source.beam_size.z, 
    10061003            {"unit": datainfo.source.beam_size_unit}) 
    1007         if written == True: 
     1004        if written: 
    10081005            self.append(size, source) 
    10091006 
     
    10611058                    size, "z", aperture.size.z, 
    10621059                    {"unit": aperture.size_unit}) 
    1063                 if written == True: 
     1060                if written: 
    10641061                    self.append(size, apert) 
    10651062 
     
    10841081            written = written | self.write_node(det, "SDD", item.distance, 
    10851082                                                {"unit": item.distance_unit}) 
    1086             if written == True: 
     1083            if written: 
    10871084                self.append(det, instr) 
    10881085 
     
    10941091            written = written | self.write_node(off, "z", item.offset.z, 
    10951092                                                {"unit": item.offset_unit}) 
    1096             if written == True: 
     1093            if written: 
    10971094                self.append(off, det) 
    10981095 
     
    11061103                                                item.orientation.z, 
    11071104                                                {"unit": item.orientation_unit}) 
    1108             if written == True: 
     1105            if written: 
    11091106                self.append(ori, det) 
    11101107 
     
    11181115                                                item.beam_center.z, 
    11191116                                                {"unit": item.beam_center_unit}) 
    1120             if written == True: 
     1117            if written: 
    11211118                self.append(center, det) 
    11221119 
     
    11281125            written = written | self.write_node(pix, "z", item.pixel_size.z, 
    11291126                                                {"unit": item.pixel_size_unit}) 
    1130             if written == True: 
     1127            if written: 
    11311128                self.append(pix, det) 
    11321129            self.write_node(det, "slit_length", item.slit_length, 
  • src/sas/sascalc/dataloader/readers/cansas_reader_HDF5.py

    rc416a17 rb8080e1  
    99import sys 
    1010 
    11 from sas.sascalc.dataloader.data_info import plottable_1D, plottable_2D,\ 
     11from ..data_info import plottable_1D, plottable_2D,\ 
    1212    Data1D, Data2D, DataInfo, Process, Aperture, Collimation, \ 
    1313    TransmissionSpectrum, Detector 
    14 from sas.sascalc.dataloader.data_info import combine_data_info_with_plottable 
    15  
    16  
    17 class Reader(): 
     14from ..data_info import combine_data_info_with_plottable 
     15from ..loader_exceptions import FileContentsException, DefaultReaderException 
     16from ..file_reader_base_class import FileReader, decode 
     17 
     18def h5attr(node, key, default=None): 
     19    return decode(node.attrs.get(key, default)) 
     20 
     21class Reader(FileReader): 
    1822    """ 
    1923    A class for reading in CanSAS v2.0 data files. The existing iteration opens 
     
    2529    Any number of SASdata sets may be present in a SASentry and the data within 
    2630    can be either 1D I(Q) or 2D I(Qx, Qy). 
     31 
    2732    Also supports reading NXcanSAS formatted HDF5 files 
    2833 
     
    3944    # Raw file contents to be processed 
    4045    raw_data = None 
    41     # Data info currently being read in 
    42     current_datainfo = None 
    43     # SASdata set currently being read in 
    44     current_dataset = None 
    4546    # List of plottable1D objects that should be linked to the current_datainfo 
    4647    data1d = None 
     
    5556    # Flag to bypass extension check 
    5657    allow_all = True 
    57     # List of files to return 
    58     output = None 
    59  
    60     def read(self, filename): 
     58 
     59    def get_file_contents(self): 
    6160        """ 
    6261        This is the general read method that all SasView data_loaders must have. 
     
    6665        """ 
    6766        # Reinitialize when loading a new data file to reset all class variables 
    68         self.reset_class_variables() 
     67        self.reset_state() 
     68 
     69        filename = self.f_open.name 
     70        self.f_open.close() # IO handled by h5py 
     71 
    6972        # Check that the file exists 
    7073        if os.path.isfile(filename): 
     
    7477            if extension in self.ext or self.allow_all: 
    7578                # Load the data file 
    76                 self.raw_data = h5py.File(filename, 'r') 
    77                 # Read in all child elements of top level SASroot 
    78                 self.read_children(self.raw_data, []) 
    79                 # Add the last data set to the list of outputs 
    80                 self.add_data_set() 
    81                 # Close the data file 
    82                 self.raw_data.close() 
    83         # Return data set(s) 
    84         return self.output 
    85  
    86     def reset_class_variables(self): 
     79                try: 
     80                    self.raw_data = h5py.File(filename, 'r') 
     81                except Exception as e: 
     82                    if extension not in self.ext: 
     83                        msg = "CanSAS2.0 HDF5 Reader could not load file {}".format(basename + extension) 
     84                        raise DefaultReaderException(msg) 
     85                    raise FileContentsException(e.message) 
     86                try: 
     87                    # Read in all child elements of top level SASroot 
     88                    self.read_children(self.raw_data, []) 
     89                    # Add the last data set to the list of outputs 
     90                    self.add_data_set() 
     91                except Exception as exc: 
     92                    raise FileContentsException(exc.message) 
     93                finally: 
     94                    # Close the data file 
     95                    self.raw_data.close() 
     96 
     97                for dataset in self.output: 
     98                    if isinstance(dataset, Data1D): 
     99                        if dataset.x.size < 5: 
     100                            self.output = [] 
     101                            raise FileContentsException("Fewer than 5 data points found.") 
     102 
     103    def reset_state(self): 
    87104        """ 
    88105        Create the reader object and define initial states for class variables 
    89106        """ 
    90         self.current_datainfo = None 
    91         self.current_dataset = None 
     107        super(Reader, self).reset_state() 
    92108        self.data1d = [] 
    93109        self.data2d = [] 
     
    95111        self.errors = set() 
    96112        self.logging = [] 
    97         self.output = [] 
    98113        self.parent_class = u'' 
    99114        self.detector = Detector() 
     
    115130            # Get all information for the current key 
    116131            value = data.get(key) 
    117             if value.attrs.get(u'canSAS_class') is not None: 
    118                 class_name = value.attrs.get(u'canSAS_class') 
    119             else: 
    120                 class_name = value.attrs.get(u'NX_class') 
     132            class_name = h5attr(value, u'canSAS_class') 
     133            if class_name is None: 
     134                class_name = h5attr(value, u'NX_class') 
    121135            if class_name is not None: 
    122136                class_prog = re.compile(class_name) 
     
    125139 
    126140            if isinstance(value, h5py.Group): 
     141                # Set parent class before recursion 
    127142                self.parent_class = class_name 
    128143                parent_list.append(key) 
     
    135150                # Recursion step to access data within the group 
    136151                self.read_children(value, parent_list) 
     152                # Reset parent class when returning from recursive method 
     153                self.parent_class = class_name 
    137154                self.add_intermediate() 
    138155                parent_list.remove(key) 
     
    165182                        self.current_dataset.x = data_set.flatten() 
    166183                    continue 
     184                elif key == u'Qdev': 
     185                    self.current_dataset.dx = data_set.flatten() 
     186                    continue 
     187                elif key == u'dQw': 
     188                    self.current_dataset.dxw = data_set.flatten() 
     189                    continue 
     190                elif key == u'dQl': 
     191                    self.current_dataset.dxl = data_set.flatten() 
     192                    continue 
    167193                elif key == u'Qy': 
    168194                    self.current_dataset.yaxis("Q_y", unit) 
     
    198224 
    199225                for data_point in data_set: 
     226                    if isinstance(data_point, np.ndarray): 
     227                        if data_point.dtype.char == 'S': 
     228                            data_point = decode(bytes(data_point)) 
     229                    else: 
     230                        data_point = decode(data_point) 
    200231                    # Top Level Meta Data 
    201232                    if key == u'definition': 
     
    203234                    elif key == u'run': 
    204235                        self.current_datainfo.run.append(data_point) 
     236                        try: 
     237                            run_name = h5attr(value, 'name') 
     238                            run_dict = {data_point: run_name} 
     239                            self.current_datainfo.run_name = run_dict 
     240                        except Exception: 
     241                            pass 
    205242                    elif key == u'title': 
    206243                        self.current_datainfo.title = data_point 
     
    411448        Data1D and Data2D objects 
    412449        """ 
    413  
    414450        # Type cast data arrays to float64 
    415451        if len(self.current_datainfo.trans_spectrum) > 0: 
     
    435471        # Type cast data arrays to float64 and find min/max as appropriate 
    436472        for dataset in self.data2d: 
    437             dataset.data = dataset.data.astype(np.float64) 
    438             dataset.err_data = dataset.err_data.astype(np.float64) 
    439             if dataset.qx_data is not None: 
    440                 dataset.xmin = np.min(dataset.qx_data) 
    441                 dataset.xmax = np.max(dataset.qx_data) 
    442                 dataset.qx_data = dataset.qx_data.astype(np.float64) 
    443             if dataset.dqx_data is not None: 
    444                 dataset.dqx_data = dataset.dqx_data.astype(np.float64) 
    445             if dataset.qy_data is not None: 
    446                 dataset.ymin = np.min(dataset.qy_data) 
    447                 dataset.ymax = np.max(dataset.qy_data) 
    448                 dataset.qy_data = dataset.qy_data.astype(np.float64) 
    449             if dataset.dqy_data is not None: 
    450                 dataset.dqy_data = dataset.dqy_data.astype(np.float64) 
    451             if dataset.q_data is not None: 
    452                 dataset.q_data = dataset.q_data.astype(np.float64) 
    453473            zeros = np.ones(dataset.data.size, dtype=bool) 
    454474            try: 
     
    473493                dataset.x_bins = dataset.qx_data[:n_cols] 
    474494                dataset.data = dataset.data.flatten() 
    475  
    476             final_dataset = combine_data_info_with_plottable( 
    477                 dataset, self.current_datainfo) 
    478             self.output.append(final_dataset) 
     495            self.current_dataset = dataset 
     496            self.send_to_output() 
    479497 
    480498        for dataset in self.data1d: 
    481             if dataset.x is not None: 
    482                 dataset.x = dataset.x.astype(np.float64) 
    483                 dataset.xmin = np.min(dataset.x) 
    484                 dataset.xmax = np.max(dataset.x) 
    485             if dataset.y is not None: 
    486                 dataset.y = dataset.y.astype(np.float64) 
    487                 dataset.ymin = np.min(dataset.y) 
    488                 dataset.ymax = np.max(dataset.y) 
    489             if dataset.dx is not None: 
    490                 dataset.dx = dataset.dx.astype(np.float64) 
    491             if dataset.dxl is not None: 
    492                 dataset.dxl = dataset.dxl.astype(np.float64) 
    493             if dataset.dxw is not None: 
    494                 dataset.dxw = dataset.dxw.astype(np.float64) 
    495             if dataset.dy is not None: 
    496                 dataset.dy = dataset.dy.astype(np.float64) 
    497             final_dataset = combine_data_info_with_plottable( 
    498                 dataset, self.current_datainfo) 
    499             self.output.append(final_dataset) 
     499            self.current_dataset = dataset 
     500            self.send_to_output() 
    500501 
    501502    def add_data_set(self, key=""): 
     
    579580        :return: unit for the value passed to the method 
    580581        """ 
    581         unit = value.attrs.get(u'units') 
     582        unit = h5attr(value, u'units') 
    582583        if unit is None: 
    583             unit = value.attrs.get(u'unit') 
     584            unit = h5attr(value, u'unit') 
    584585        # Convert the unit formats 
    585586        if unit == "1/A": 
  • src/sas/sascalc/dataloader/readers/danse_reader.py

    rcee5c78 rb8080e1  
    157157        # Store all data 
    158158        # Store wavelength 
    159         if has_converter == True and self.current_datainfo.source.wavelength_unit != 'A': 
     159        if has_converter and self.current_datainfo.source.wavelength_unit != 'A': 
    160160            conv = Converter('A') 
    161161            wavelength = conv(wavelength, 
     
    164164 
    165165        # Store distance 
    166         if has_converter == True and detector.distance_unit != 'm': 
     166        if has_converter and detector.distance_unit != 'm': 
    167167            conv = Converter('m') 
    168168            distance = conv(distance, units=detector.distance_unit) 
     
    170170 
    171171        # Store pixel size 
    172         if has_converter == True and detector.pixel_size_unit != 'mm': 
     172        if has_converter and detector.pixel_size_unit != 'mm': 
    173173            conv = Converter('mm') 
    174174            pixel = conv(pixel, units=detector.pixel_size_unit) 
     
    191191        x_vals = np.tile(x_vals, (size_y, 1)).flatten() 
    192192        y_vals = np.tile(y_vals, (size_x, 1)).T.flatten() 
    193         if (np.all(self.current_dataset.err_data is None) 
     193        if (np.all(self.current_dataset.err_data == None) 
    194194                or np.any(self.current_dataset.err_data <= 0)): 
    195195            new_err_data = np.sqrt(np.abs(self.current_dataset.data)) 
  • src/sas/sascalc/dataloader/readers/sesans_reader.py

    r849094a rb8080e1  
    1212from ..file_reader_base_class import FileReader 
    1313from ..data_info import plottable_1D, DataInfo 
    14 from ..loader_exceptions import FileContentsException, DataReaderException 
     14from ..loader_exceptions import FileContentsException 
    1515 
    1616# Check whether we have a converter available 
     
    1818try: 
    1919    from sas.sascalc.data_util.nxsunit import Converter 
    20 except: 
     20except ImportError: 
    2121    has_converter = False 
    2222_ZERO = 1e-16 
     
    4646        line = self.nextline() 
    4747        params = {} 
    48         while not line.startswith("BEGIN_DATA"): 
     48        while line and not line.startswith("BEGIN_DATA"): 
    4949            terms = line.split() 
    5050            if len(terms) >= 2: 
     
    6363            raise FileContentsException("Wavelength has no units") 
    6464        if params["SpinEchoLength_unit"] != params["Wavelength_unit"]: 
    65             raise FileContentsException("The spin echo data has rudely used " 
    66                                "different units for the spin echo length " 
    67                                "and the wavelength.  While sasview could " 
    68                                "handle this instance, it is a violation " 
    69                                "of the file format and will not be " 
    70                                "handled by other software.") 
     65            raise FileContentsException( 
     66                "The spin echo data has rudely used " 
     67                "different units for the spin echo length " 
     68                "and the wavelength.  While sasview could " 
     69                "handle this instance, it is a violation " 
     70                "of the file format and will not be " 
     71                "handled by other software.") 
    7172 
    7273        headers = self.nextline().split() 
     
    8687 
    8788        if not data.size: 
    88             raise FileContentsException("{} is empty".format(path)) 
     89            raise FileContentsException("{} is empty".format(self.filepath)) 
    8990        x = data[:, headers.index("SpinEchoLength")] 
    9091        if "SpinEchoLength_error" in headers: 
  • src/sas/sascalc/file_converter/otoko_loader.py

    r0b1a677 rb8080e1  
    3636 
    3737        Given the paths of two header files, this function will load each axis in 
    38         turn.  If loading is successfull then an instance of the OTOKOData class 
     38        turn.  If loading is successful then an instance of the OTOKOData class 
    3939        will be returned, else an exception will be raised. 
    4040 
  • src/sas/sascalc/fit/AbstractFitEngine.py

    racd9c311 rb8080e1  
    7878    def get_params(self, fitparams): 
    7979        """ 
    80         return a list of value of paramter to fit 
    81  
    82         :param fitparams: list of paramaters name to fit 
     80        return a list of value of parameter to fit 
     81 
     82        :param fitparams: list of parameters name to fit 
    8383 
    8484        """ 
  • src/sas/sascalc/fit/MultiplicationModel.py

    r574adc7 rb8080e1  
    6868        try: 
    6969            multiplicity = p_model.multiplicity 
    70         except: 
     70        except AttributeError: 
    7171            multiplicity = 1 
    7272        ## functional multiplicity of the model 
     
    7676        self.non_fittable = p_model.non_fittable 
    7777        self.multiplicity_info = [] 
    78         self.fun_list = {} 
     78        self.fun_list = [] 
    7979        if self.non_fittable > 1: 
    8080            try: 
     
    8282                self.fun_list = p_model.fun_list 
    8383                self.is_multiplicity_model = True 
    84             except: 
     84            except AttributeError: 
    8585                pass 
    8686        else: 
  • src/sas/sascalc/fit/pagestate.py

    r9e6aeaf rb8080e1  
    1313################################################################################ 
    1414import time 
     15import re 
    1516import os 
    1617import sys 
     
    646647                    name = value.split(':', 1)[1].strip() 
    647648                    file_value = "File name:" + name 
     649                    #Truncating string so print doesn't complain of being outside margins 
     650                    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:] 
    648654                    file_name = CENTRE % file_value 
    649655                    if len(title) == 0: 
     
    721727        html_str, text_str, title = self._get_report_string() 
    722728        # Allow 2 figures to append 
    723         image_links = [FEET_2%fig for fig in fig_urls] 
    724  
     729        #Constraining image width for OSX and linux, so print doesn't complain of being outside margins 
     730        if sys.platform == "win32": 
     731            image_links = [FEET_2%fig for fig in fig_urls] 
     732        else: 
     733            image_links = [FEET_2_unix%fig for fig in fig_urls] 
    725734        # final report html strings 
    726735        report_str = html_str + ELINE.join(image_links) 
    727  
     736        report_str += FEET_3 
    728737        return report_str, text_str 
    729738 
     
    954963        if node.get('version'): 
    955964            # Get the version for model conversion purposes 
    956             self.version = tuple(int(e) for e in 
    957                                  str.split(node.get('version'), ".")) 
     965            x = re.sub('[^\d.]', '', node.get('version')) 
     966            self.version = tuple(int(e) for e in str.split(x, ".")) 
    958967            # The tuple must be at least 3 items long 
    959968            while len(self.version) < 3: 
     
    13681377""" 
    13691378FEET_2 = \ 
    1370 """<img src="%s" ></img> 
     1379"""<img src="%s"></img> 
     1380""" 
     1381FEET_2_unix = \ 
     1382"""<img src="%s" width="540"></img> 
    13711383""" 
    13721384FEET_3 = \ 
  • src/sas/sascalc/fit/qsmearing.py

    r50fcb09 rb8080e1  
    9090            #print "data1D.dx[0]",data1D.dx[0],data1D.dxl[0] 
    9191    # If we found resolution smearing data, return a QSmearer 
    92     if _found_resolution == True: 
     92    if _found_resolution: 
    9393         return pinhole_smear(data, model) 
    9494 
     
    113113                break 
    114114    # If we found slit smearing data, return a slit smearer 
    115     if _found_slit == True: 
     115    if _found_slit: 
    116116        return slit_smear(data, model) 
    117117    return None 
  • src/sas/sascalc/pr/c_extensions/Cinvertor.c

    rd04ac05 rb8080e1  
    735735 
    736736const char get_peaks_doc[] = 
    737         "Returns the number of peaks in the output P(r) distrubution\n" 
     737        "Returns the number of peaks in the output P(r) distribution\n" 
    738738        "for the given set of coefficients.\n" 
    739739        " @param args: c-parameters\n" 
  • src/sas/sascalc/pr/fit/AbstractFitEngine.py

    r574adc7 rb8080e1  
    7878    def get_params(self, fitparams): 
    7979        """ 
    80         return a list of value of paramter to fit 
    81  
    82         :param fitparams: list of paramaters name to fit 
     80        return a list of value of parameter to fit 
     81 
     82        :param fitparams: list of parameters name to fit 
    8383 
    8484        """ 
  • src/sas/sascalc/pr/invertor.py

    r6da860a rb8080e1  
    222222        elif name == 'est_bck': 
    223223            value = self.get_est_bck() 
    224             if value == 1: 
    225                 return True 
    226             else: 
    227                 return False 
     224            return value == 1 
    228225        elif name in self.__dict__: 
    229226            return self.__dict__[name] 
     
    460457 
    461458        # If we need to fit the background, add a term 
    462         if self.est_bck == True: 
     459        if self.est_bck: 
    463460            nfunc_0 = nfunc 
    464461            nfunc += 1 
     
    500497            cov = np.linalg.pinv(inv_cov) 
    501498            err = math.fabs(chi2 / float(npts - nfunc)) * cov 
    502         except Exception as ex: 
     499        except: 
    503500            # We were not able to estimate the errors 
    504501            # Return an empty error matrix 
    505             logger.error(ex) 
     502            logger.error(sys.exc_value) 
    506503 
    507504        # Keep a copy of the last output 
    508         if self.est_bck == False: 
     505        if not self.est_bck: 
    509506            self.out = c 
    510507            self.cov = err 
     
    540537 
    541538        """ 
    542         from sas.sascalc.pr.num_term import NTermEstimator 
     539        from .num_term import NTermEstimator 
    543540        estimator = NTermEstimator(self.clone()) 
    544541        try: 
    545542            return estimator.num_terms(isquit_func) 
    546         except Exception as ex: 
     543        except: 
    547544            # If we fail, estimate alpha and return the default 
    548545            # number of terms 
    549546            best_alpha, _, _ = self.estimate_alpha(self.nfunc) 
    550             logger.warning("Invertor.estimate_numterms: %s" % ex) 
     547            logger.warning("Invertor.estimate_numterms: %s" % sys.exc_value) 
    551548            return self.nfunc, best_alpha, "Could not estimate number of terms" 
    552549 
     
    634631                return best_alpha, message, elapsed 
    635632 
    636         except Exception as ex: 
    637             message = "Invertor.estimate_alpha: %s" % ex 
     633        except: 
     634            message = "Invertor.estimate_alpha: %s" % sys.exc_value 
    638635            return 0, message, elapsed 
    639636 
     
    658655        file.write("#slit_width=%g\n" % self.slit_width) 
    659656        file.write("#background=%g\n" % self.background) 
    660         if self.est_bck == True: 
     657        if self.est_bck: 
    661658            file.write("#has_bck=1\n") 
    662659        else: 
     
    738735                    elif line.startswith('#has_bck='): 
    739736                        toks = line.split('=') 
    740                         if int(toks[1]) == 1: 
    741                             self.est_bck = True 
    742                         else: 
    743                             self.est_bck = False 
     737                        self.est_bck = int(toks[1]) == 1 
    744738 
    745739                    # Now read in the parameters 
     
    754748                        self.cov[i][i] = float(toks2[1]) 
    755749 
    756             except Exception as ex: 
    757                 msg = "Invertor.from_file: corrupted file\n%s" % ex 
     750            except: 
     751                msg = "Invertor.from_file: corrupted file\n%s" % sys.exc_value 
    758752                raise RuntimeError(msg) 
    759753        else: 
  • src/sas/sascalc/pr/num_term.py

    r8f83719f rb8080e1  
    5555        medi = 0 
    5656        for i in range(dv): 
    57             if odd == True: 
     57            if odd: 
    5858                medi = osc[int(med)] 
    5959            else: 
     
    9898                new_osc3.append(self.osc_list[i]) 
    9999 
    100         if flag9 == True: 
     100        if flag9: 
    101101            self.dataset = new_osc1 
    102         elif flag8 == True: 
     102        elif flag8: 
    103103            self.dataset = new_osc2 
    104104        else: 
     
    141141            div = len(nts) 
    142142            tem = float(div) / 2.0 
    143             odd = self.is_odd(div) 
    144             if odd == True: 
     143            if self.is_odd(div): 
    145144                nt = nts[int(tem)] 
    146145            else: 
     
    148147            return nt, self.alpha_list[nt - 10], self.mess_list[nt - 10] 
    149148        except: 
    150             #TODO: check the logic above and make sure it doesn't  
     149            #TODO: check the logic above and make sure it doesn't 
    151150            # rely on the try-except. 
    152151            return self.nterm_min, self.invertor.alpha, '' 
     
    183182                data_y = np.append(data_y, test_y) 
    184183                data_err = np.append(data_err, err) 
    185             except Exception as ex: 
    186                 logger.error(ex) 
     184            except: 
     185                logger.error(sys.exc_value) 
    187186 
    188187    return data_x, data_y, data_err 
Note: See TracChangeset for help on using the changeset viewer.