numpy.nanmax

Here are the examples of the python api numpy.nanmax taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

36 Examples 7

Example 1

Project: auto-sklearn Source File: regression.py
Function: fit_estimator
    def fit_estimator(self, X, y, fit_params=None):
        self.y_max_ = np.nanmax(y)
        self.y_min_ = np.nanmin(y)
        if fit_params is None:
            fit_params = {}
        return super(SimpleRegressionPipeline, self).fit_estimator(
            X, y, **fit_params)

Example 2

Project: auto-sklearn Source File: regression.py
Function: iterative_fit
    def iterative_fit(self, X, y, fit_params=None, n_iter=1):
        self.y_max_ = np.nanmax(y)
        self.y_min_ = np.nanmin(y)
        if fit_params is None:
            fit_params = {}
        return super(SimpleRegressionPipeline, self).iterative_fit(
            X, y, n_iter=n_iter, **fit_params)

Example 3

Project: pyqtgraph Source File: ImageView.py
    def quickMinMax(self, data):
        """
        Estimate the min/max values of *data* by subsampling.
        """
        while data.size > 1e6:
            ax = np.argmax(data.shape)
            sl = [slice(None)] * data.ndim
            sl[ax] = slice(None, None, 2)
            data = data[sl]
        return nanmin(data), nanmax(data)

Example 4

Project: fluff Source File: plot.py
Function: load_data
    def _load_data(self, interval):
        self.profile = self.track.get_profile(interval, 
                scalepm=self.scalepm)

        if not self.ymax:
            self.ymax = np.nanmax(self.profile) * 1.10

Example 5

Project: spotpy Source File: analyser.py
def get_maxlikeindex(results):
    """
    Get the maximum objectivefunction of your result array
    
    :results: Expects an numpy array which should of an index "like" for objectivefunctions 
    :type: array    
    
    :return: Index of the position in the results array with the maximum objectivefunction
        value and value of the maximum objectivefunction of your result array
    :rtype: int and float
    """        
    maximum=np.nanmax(results['like'])
    value=str(round(maximum,4))
    text=str('The best model run has an objectivefunction of: ')
    textv=text+value
    print(textv)
    index=np.where(results['like']==maximum)
    return index, maximum

Example 6

Project: datashader Source File: utils.py
def summarize_aggregate_values(aggregate, how='linear', num=180):
    """Helper function similar to np.linspace which return values from aggregate min value to aggregate max value in either linear or log space.
    """

    max_val = np.nanmax(aggregate.values)
    min_val = np.nanmin(aggregate.values)

    if min_val == 0:
        min_val = aggregate.data[aggregate.data > 0].min()

    if how == 'linear':
        vals = np.linspace(min_val, max_val, num)[None, :]
    else:
        vals = (np.logspace(0,
                            np.log1p(max_val - min_val),
                            base=np.e, num=num,
                            dtype=min_val.dtype) + min_val)[None, :]

    return DataArray(vals), min_val, max_val

Example 7

Project: pydem Source File: processing_manager.py
    def fill_max_elevations(self):
        max_elev = {}
        for fn in self.edges.keys():
            elev_file = GdalReader(file_name=fn)
            elev, = elev_file.raster_layers
            max_elev[fn] = np.nanmax(elev.raster_data)
            del elev_file  # close file
            del elev
        self.max_elev = max_elev

Example 8

Project: chaco Source File: data_cube.py
Function: compute_model
    @on_trait_change("npts_+", "min_+", "max_+")
    def compute_model(self):
        def vfunc(x, y, z):
            return sin(x*z) * cos(y)*sin(z) + sin(0.5*z)

        # Create the axes
        self.xs = linspace(self.min_x, self.max_x, self.npts_x)
        self.ys = linspace(self.min_y, self.max_y, self.npts_y)
        self.zs = linspace(self.min_z, self.max_z, self.npts_z)

        # Generate a cube of values by using newaxis to span new dimensions
        self.vals = vfunc(self.xs[:, newaxis, newaxis],
                          self.ys[newaxis, :, newaxis],
                          self.zs[newaxis, newaxis, :])

        self.minval = nanmin(self.vals)
        self.maxval = nanmax(self.vals)
        self.model_changed = True

Example 9

Project: mayavi Source File: test_threshold_filter.py
    def test_threshold_filter_threhsold(self):
        src = self.make_src()
        self.e.add_source(src)
        threshold = Threshold()
        self.e.add_filter(threshold)
        threshold.upper_threshold = 20.
        self.assertTrue(
            20 >= np.nanmax(
                threshold.get_output_dataset().point_data.scalars.to_array()
            )
        )
        return

Example 10

Project: nansat Source File: test_radarsat2.py
    def resize(self, rsfile):
        sys.stderr.write('\nresize:'+rsfile+'\n')
        n = Nansat(rsfile)
        inc_max = float(n.get_metadata()['FAR_RANGE_INCIDENCE_ANGLE'])+0.5
        n.resize(0.5, eResampleAlg=0)
        assert (np.nanmax(n['incidence_angle']) <= inc_max)
        n.undo()
        n.resize(0.5, eResampleAlg=1)
        assert (np.nanmax(n['incidence_angle']) <= inc_max)
        n.undo()
        n.resize(0.5, eResampleAlg=2)
        assert (np.nanmax(n['incidence_angle']) <= inc_max)
        n.undo()
        n.resize(0.5, eResampleAlg=3)
        assert (np.nanmax(n['incidence_angle']) <= inc_max)
        n.undo()
        n.resize(0.5, eResampleAlg=4)
        assert (np.nanmax(n['incidence_angle']) <= inc_max)
        n.undo()

Example 11

Project: numba Source File: arraymath.py
@overload(np.nanmax)
def np_nanmax(a):
    if not isinstance(a, types.Array):
        return
    isnan = get_isnan(a.dtype)

    def nanmax_impl(a):
        if a.size == 0:
            raise ValueError("nanmin(): empty array")
        for view in np.nditer(a):
            maxval = view.item()
            break
        for view in np.nditer(a):
            v = view.item()
            if not maxval > v and not isnan(v):
                maxval = v
        return maxval

    return nanmax_impl

Example 12

Project: auto-sklearn Source File: metafeatures.py
Function: calculate
    def _calculate(self, X, y, categorical):
        kurts = helper_functions.get_value("Kurtosisses")
        maximum = np.nanmax(kurts) if len(kurts) > 0 else 0
        return maximum if np.isfinite(maximum) else 0

Example 13

Project: auto-sklearn Source File: metafeatures.py
Function: calculate
    def _calculate(self, X, y, categorical):
        skews = helper_functions.get_value("Skewnesses")
        maximum = np.nanmax(skews) if len(skews) > 0 else 0
        return maximum if np.isfinite(maximum) else 0

Example 14

Project: fits2hdf Source File: quinoa.py
def couscous_scale(data):
    """ Apply couscous scaling to data

    (ceiling rounding and converion to int) """

    d_max = np.nanmax(data)
    d_min = np.nanmin(data)

    if d_max <= 2**8 and d_min >= -2**8:
        scale_factor = 2**16
        data *= scale_factor
        data = np.ceil(data).astype("int32")
    if d_max <= 2**15 and d_min >= -2**15:
        data = np.ceil(data).astype("int16")
        scale_factor = 1
    elif d_max <= 2**31 and d_min >= -2**31:
        data = np.ceil(data).astype("int32")
        scale_factor = 1
    else:
        scale_factor = d_max * 2**32
        data_zeroed = (data - d_min) / scale_factor
        data = np.ceil(data_zeroed).astype("int32")

    scale_dict = {
        'data': data,
        'min': d_min,
        'max': d_max,
        'scale_factor': scale_factor,
        'dtype': str(data.dtype)

    }
    return scale_dict

Example 15

Project: python-gsw Source File: test_profiles.py
Function: generic_test
def generic_test(self, func=None, argnames=None):
    """Generic test function, to be specialized by functools.partial."""
    # Transform argument names to name convention in cv dataset.
    args = [getattr(cv, a + '_chck_cast') for a in argnames]
    # Perform the function call
    out = getattr(gsw, func)(*args)
    # FIXME: Testing just the first output!
    # Check that the maximal error is less than the given tolerance
    if isinstance(out, tuple):
        out = out[0]
        # print("""%s returns a tuple.""" % func)
    target = getattr(cv, func)
    maxdiff = np.nanmax(abs(out - target))
    maxallowed = getattr(cv, func + '_ca')
    try:
        self.assertTrue(maxdiff < maxallowed)
    except AssertionError as e:
        print(out)
        print(target)
        raise AssertionError("Error in %s %s, maxdiff is %s vs %s allowed" %
                             (func, e.args, maxdiff, maxallowed))

Example 16

Project: spotpy Source File: analyser.py
def get_best_parameterset(results,maximize=True):
    """
    Get the best parameter set of your result array, depending on your first objectivefunction 
    
    :results: Expects an numpy array which should have as first axis an index "like" or "like1". 
    :type: array  
    
    :maximize: Optional, default=True meaning the highest objectivefunction is taken as best, if False the lowest objectivefunction is taken as best.
    :type: boolean
    
    :return: Best parameter set
    :rtype: array
    """
    try:
        likes=results['like']
    except ValueError:
        likes=results['like1']
    if maximize:
        best=np.nanmax(likes)
    else:
        best=np.nanmin(likes)
    index=np.where(likes==best)
    return get_parameters(results[index])

Example 17

Project: datashader Source File: reductions.py
Function: combine
    @staticmethod
    def _combine(aggs):
        return np.nanmax(aggs, axis=0)

Example 18

Project: chaco Source File: multi_array_data_source.py
    def get_bounds(self, value = None, index = None):
        """get_bounds() -> tuple(min, max)

        Returns a tuple (min, max) of the bounding values for the data source.
        In the case of 2-D data, min and max are 2-D points that represent the
        bounding corners of a rectangle enclosing the data set.  Note that
        these values are not view-dependent, but represent intrinsic properties
        of the data source.

        If data is the empty set, then the min and max vals are 0.0.

        If *value* and *index* are both None, then the method returns the
        global minimum and maximum for the entire data set.
        If *value* is an integer, then the method returns the minimum and
        maximum along the *value* slice in the **value_dimension**.
        If *index* is an integer, then the method returns the minimum and
        maximum along the *index* slice in the **index_direction**.
        """

        if self._data is None or 0 in self._data.shape:
            return (0.0, 0.0)

        if type(value) == int:
            if self.value_dimension == 0:
                maxi = nanmax(self._data[value, ::])
                mini = nanmin(self._data[value, ::])
            else:
                # value_dimension == 1
                maxi = nanmax(self._data[::, value])
                mini = nanmin(self._data[::, value])
        elif type(index) == int:
            if self.index_dimension == 0:
                maxi = nanmax(self._data[index, ::])
                mini = nanmin(self._data[index, ::])
            else:
                # index_dimension == 1
                maxi = nanmax(self._data[::, index])
                mini = nanmin(self._data[::, index])
        else:
            # value is None and index is None:
            maxi = nanmax(self._data)
            mini = nanmin(self._data)

        return (mini, maxi)

Example 19

Project: chaco Source File: data_cube.py
Function: compute_model
    def compute_model(self):
        global dl_path
        mrbrain_path = os.path.join(dl_path, 'voldata', 'MRbrain.')
        nx = 256
        ny = 256
        nz = 109
        full_arr = zeros((nx, ny, nz), dtype='f')
        for i in range(1, 110):
            arr = fromfile(mrbrain_path + str(i), dtype='>u2')
            arr.shape = (256,256)
            full_arr[:,:,i-1] = arr
        self.vals = full_arr

        # Create the axes
        self.xs = arange(nx)
        self.ys = arange(ny)
        self.zs = arange(nz)

        # Generate a cube of values by using newaxis to span new dimensions
        self.minval = nanmin(self.vals)
        self.maxval = nanmax(self.vals)
        self.model_changed = True

Example 20

Project: chaco Source File: scalar_image_function_inspector.py
Function: compute_model
    def compute_model(self):
        # The xs and ys used for the image plot range need to be the
        # edges of the cells.
        self.xs = linspace(self.min_x, self.max_x, self.npts_x+1)
        self.ys = linspace(self.min_y, self.max_y, self.npts_y+1)

        # The grid of points at which we will evaluate the 2D function
        # is located at cell centers, so use halfsteps from the
        # min/max values (which are edges)
        xstep = (self.max_x - self.min_x) / self.npts_x
        #ystep = (self.max_y - self.min_y) / self.npts_y
        gridx = linspace(self.min_x+xstep/2, self.max_x-xstep/2, self.npts_x)
        gridy = linspace(self.min_y+xstep/2, self.max_y-xstep/2, self.npts_y)
        x, y = meshgrid(gridx, gridy)
        try:
            d = dict(x=x, y=y)
            exec("from scipy import *", d)
            exec("from scipy.special import *", d)
            self.zs = eval(self.function, d)
            self.minz = nanmin(self.zs)
            self.maxz = nanmax(self.zs)
            self.model_changed = True
            self._function = self.function
        except:
            self.set(function = self._function, trait_change_notify=False)

Example 21

Project: chaco Source File: scalar_image_function_inspector_old.py
Function: compute_model
    def compute_model(self):
        # The xs and ys used for the image plot range need to be the
        # edges of the cells.
        self.xs = linspace(self.min_x, self.max_x, self.npts_x+1)
        self.ys = linspace(self.min_y, self.max_y, self.npts_y+1)

        # The grid of points at which we will evaluate the 2D function
        # is located at cell centers, so use halfsteps from the
        # min/max values (which are edges)
        xstep = (self.max_x - self.min_x) / self.npts_x
        ystep = (self.max_y - self.min_y) / self.npts_y
        gridx = linspace(self.min_x+xstep/2, self.max_x-xstep/2, self.npts_x)
        gridy = linspace(self.min_y+xstep/2, self.max_y-xstep/2, self.npts_y)
        x, y = meshgrid(gridx, gridy)
        try:
            d = dict(x=x, y=y)
            exec("from scipy import *", d)
            exec("from scipy.special import *", d)
            self.zs = eval(self.function, d)
            self.minz = nanmin(self.zs)
            self.maxz = nanmax(self.zs)
            self.model_changed = True
            self._function = self.function
        except:
            self.set(function = self._function, trait_change_notify=False)

Example 22

Project: chaco Source File: multi_line_plot.py
    def __init__(self, x_index, y_index, data, **kw):
        super(MyPlot, self).__init__(**kw)

        # Create the data source for the MultiLinePlot.
        ds = MultiArrayDataSource(data=data)

        xs = ArrayDataSource(x_index, sort_order='ascending')
        xrange = DataRange1D()
        xrange.add(xs)

        ys = ArrayDataSource(y_index, sort_order='ascending')
        yrange = DataRange1D()
        yrange.add(ys)

        mlp = MultiLinePlot(
                        index = xs,
                        yindex = ys,
                        index_mapper = LinearMapper(range=xrange),
                        value_mapper = LinearMapper(range=yrange),
                        value=ds,
                        global_max = np.nanmax(data),
                        global_min = np.nanmin(data),
                        **kw)

        self.plot = Plot()
        self.plot.add(mlp)

Example 23

Project: hyperspy Source File: utils.py
def _make_cascade_subplot(
        spectra, ax, color="blue", line_style='-', padding=1):
    max_value = 0
    for spectrum in spectra:
        spectrum_yrange = (np.nanmax(spectrum.data) -
                           np.nanmin(spectrum.data))
        if spectrum_yrange > max_value:
            max_value = spectrum_yrange
    if isinstance(color, str):
        color = [color] * len(spectra)
    if isinstance(line_style, str):
        line_style = [line_style] * len(spectra)
    for spectrum_index, (spectrum, color, line_style) in enumerate(
            zip(spectra, color, line_style)):
        x_axis = spectrum.axes_manager.signal_axes[0]
        data_to_plot = ((spectrum.data - spectrum.data.min()) /
                        float(max_value) + spectrum_index * padding)
        ax.plot(x_axis.axis, data_to_plot, color=color, ls=line_style)
    _set_spectrum_xlabel(spectra if isinstance(spectra, hs.signals.BaseSignal)
                         else spectra[-1], ax)
    ax.set_yticks([])
    ax.autoscale(tight=True)

Example 24

Project: apogee Source File: plot.py
@specPlotInputDecorator
def windows(*args,**kwargs):
    """
    NAME:
       windows
    PURPOSE:
       plot the spectral windows for a given element
    INPUT:
       Either:
          (a) wavelength, spectrum (\AA,spectrum units)
          (b) spectrum (assumed on standard APOGEE re-sampled wavelength grid)
          (c) location ID, APOGEE ID (default loads aspcapStar, loads extension ext(=1); apStar=True loads apStar spectrum)
          +element string (e.g., 'Al'); Adding 1 and 2 splits the windows into two
    KEYWORDS:
       plot_weights= (False) if True, also plot the weights for the windows (assumes that the spectrum is on the apStarWavegrid)
       markLines= mark the location of 'lines' (see apogee.spec.window.lines)
       apogee.spec.plot.waveregions keywords
    OUTPUT:
       plot to output
       The final axes allow one to put additional labels on the plot, e.g., for adding the APOGEE ID:
       bovy_plot.bovy_text(r'$\mathrm{%s}$' % '2M02420597+0837017',top_left=True)       
       Note that an ID (e.g., the apogee ID) and Teff, logg, metallicity, and alpha-enhancement labels can be added using the keywords label* above
    HISTORY:
       2015-01-26 - Written (based on older code) - Bovy (IAS)
    """
    pad= kwargs.pop('pad',3)
    try:
        si,ei= apwindow.waveregions(args[2],pad=pad,asIndex=True)
    except IOError:
        try:
            si, ei= apwindow.waveregions(args[2][:-1],pad=pad,asIndex=True)
        except IOError:
            raise IOError("Windows for element %s could not be loaded, please specify an existing APOGEE element" % ((args[2].lower().capitalize())))
        if args[2][-1] == '1':
            si= si[:len(si)//2]
            ei= ei[:len(ei)//2]
        else:
            si= si[len(si)//2:]
            ei= ei[len(ei)//2:]
        # Remove the number from the element
        newargs= (args[0],args[1],args[2][:-1])
        for ii in range(len(args)-3):
            newargs= newargs+(args[ii+3],)
        args= newargs
    # Also get the number and total width of all of the windows
    dlam= apwindow.total_dlambda(args[2],pad=pad)
    numw= apwindow.num(args[2])
    # Set spacing between windows
    if numw > 20:
        kwargs['skipdx']= 0.003
        kwargs['_noskipdiags']= True
    elif numw > 15:
        kwargs['skipdx']= 0.01
    # Set initial space to zero
    kwargs['_startendskip']= 0
    # Set initial figure width
    if not kwargs.get('overplot',False) and not 'fig_width' in kwargs:
        if dlam > 150.:
            kwargs['fig_width']= 8.4
        else:
            kwargs['fig_width']= 4.2
    # Don't tick x
    kwargs['_noxticks']= True
    # Label the largest wavelength in angstrom
    kwargs['_labelwav']= True
    # Don't label the lines unless explicitly asked for
    kwargs['labelLines']= kwargs.get('labelLines',False)
    # Plot the weights as well
    if kwargs.pop('plot_weights',False):
        kwargs['_plotw']= apwindow.read(args[2],apStarWavegrid=True)
        if kwargs.get('apStar',False):
            kwargs['yrange']= kwargs.get('yrange',
                                         [0.,1.1*numpy.nanmax(args[1])])
        else:
            kwargs['yrange']= kwargs.get('yrange',[0.,1.2])
    # mark the 'lines'
    markLines= kwargs.get('markLines',not 'overplot' in kwargs)
    if markLines and not '_markwav' in kwargs:
        kwargs['_markwav']= apwindow.lines(args[2])
    # Plot
    waveregions(args[0],args[1],startindxs=si,endindxs=ei,
                *args[3:],**kwargs)
    # Add label
    bovy_plot.bovy_text(r'$\mathrm{%s}$' % ((args[2].lower().capitalize())),
                        top_left=True,fontsize=10,backgroundcolor='w')
    return None

Example 25

Project: pylinac Source File: roi.py
Function: max
    @property
    def max(self):
        """The max pixel value of the ROI."""
        masked_img = self.circle_mask()
        return np.nanmax(masked_img)

Example 26

Project: pylearn2 Source File: general.py
Function: contains_inf
def contains_inf(arr):
    """
    Test whether a numpy.ndarray contains any `np.inf` values.

    Parameters
    ----------
    arr : np.ndarray

    Returns
    -------
    contains_inf : bool
        `True` if the array contains any `np.inf` values, `False` otherwise.

    Notes
    -----
    Tests for the presence of `np.inf`'s by determining whether the
    values returned by `np.nanmin(arr)` and `np.nanmax(arr)` are finite.
    This approach is more memory efficient than the obvious alternative,
    calling `np.any(np.isinf(ndarray))`, which requires the construction of a
    boolean array with the same shape as the input array.
    """
    return np.isinf(np.nanmax(arr)) or np.isinf(np.nanmin(arr))

Example 27

Project: agent-trainer Source File: episode.py
    def _learn_from_memories(self, replay_memories, q_network, global_step):
        if self._pre_learning_stage(global_step):
            loss = 0.0
            return loss

        sampled_replay_memories = replay_memories.sample(sample_size=self.hyperparameters.REPLAY_MEMORIES_TRAIN_SAMPLE_SIZE,
                                                         recent_memories_span=self.hyperparameters.REPLAY_MEMORIES_RECENT_SAMPLE_SPAN)
        consequent_states = [replay_memory.consequent_state for replay_memory in sampled_replay_memories]
        max_q_consequent_states = np.nanmax(q_network.forward_pass_batched(consequent_states), axis=1)

        train_bundles = [None] * self.hyperparameters.REPLAY_MEMORIES_TRAIN_SAMPLE_SIZE
        discount_factor = self.hyperparameters.Q_UPDATE_DISCOUNT_FACTOR
        for idx, replay_memory in enumerate(sampled_replay_memories):
            target_action_q_value = float(self._q_target(replay_memory=replay_memory,
                                                         max_q_consequent_state=max_q_consequent_states[idx],
                                                         discount_factor=discount_factor))
            train_bundles[idx] = q_network.create_train_bundle(state=replay_memory.initial_state,
                                                               action_index=replay_memory.action_index,
                                                               target_action_q_value=target_action_q_value)

        loss = q_network.train(train_bundles, global_step - self.hyperparameters.REPLAY_MEMORIES_MINIMUM_SIZE_FOR_LEARNING)
        return loss

Example 28

Project: sima Source File: __init__.py
def to8bit(array):
    """Convert an array to 8 bit."""
    return (old_div((255. * array), nanmax(array))).astype('uint8')

Example 29

Project: sima Source File: __init__.py
def to16bit(array):
    """Convert an array to 16 bit."""
    return (old_div((65535. * array), nanmax(array))).astype('uint16')

Example 30

Project: chumpy Source File: ch_ops.py
Function: f
    def f(self, *args, **kwargs):    return np.nanmax(*args, **kwargs)
    def argf(self, *args, **kwargs): return np.nanargmax(*args, **kwargs)

Example 31

Project: pyciss Source File: ringcube.py
    @property
    def imgmax(self):
        return np.nanmax(self.img)

Example 32

Project: flopy Source File: netcdf.py
Function: append
    def append(self,other,suffix="_1"):
        assert isinstance(other,NetCdf) or isinstance(other,dict)
        if isinstance(other,NetCdf):
            for vname in other.var_attr_dict.keys():
                attrs = other.var_attr_dict[vname].copy()
                var = other.nc.variables[vname]
                new_vname = vname

                if vname in self.nc.variables.keys():
                    if vname not in STANDARD_VARS:
                        new_vname = vname + suffix
                        if "long_name" in attrs:
                            attrs["long_name"] += " " + suffix
                    else:
                        continue
                assert new_vname not in self.nc.variables.keys(),\
                    "var already exists:{0} in {1}".\
                        format(new_vname,",".join(self.nc.variables.keys()))
                attrs["max"] = var[:].max()
                attrs["min"] = var[:].min()
                new_var = self.create_variable(new_vname,attrs,
                                              var.dtype,
                                              dimensions=var.dimensions)
                new_var[:] = var[:]
        else:
            for vname,array in other.items():
                vname_norm = self.normalize_name(vname)
                assert vname_norm in self.nc.variables.keys(),"dict var not in " \
                                                         "self.vars:{0}-->".\
                                                         format(vname) +\
                                                        ",".join(self.nc.variables.keys())


                new_vname = vname_norm + suffix
                assert new_vname not in self.nc.variables.keys()
                attrs = self.var_attr_dict[vname_norm].copy()
                attrs["max"] = np.nanmax(array)
                attrs["min"] = np.nanmin(array)
                attrs["name"] = new_vname
                attrs["long_name"] = attrs["long_name"] + ' ' + suffix
                var = self.nc.variables[vname_norm]
                #assert var.shape == array.shape,\
                #    "{0} shape ({1}) doesn't make array shape ({2})".\
                #        format(new_vname,str(var.shape),str(array.shape))
                new_var = self.create_variable(new_vname,attrs,
                                              var.dtype,
                                              dimensions=var.dimensions)
                try:
                    new_var[:] = array
                except:
                    new_var[:,0] = array

        return

Example 33

Project: spinalcordtoolbox Source File: msct_image.py
Function: change_type
    def changeType(self, type=''):
        from numpy import uint8, uint16, uint32, uint64, int8, int16, int32, int64, float32, float64

        """
        Change the voxel type of the image
        :param type:    if not set, the image is saved in standard type
                        if 'minimize', image space is minimize
                        if 'minimize_int', image space is minimize and values are approximated to integers
                        (2, 'uint8', np.uint8, "NIFTI_TYPE_UINT8"),
                        (4, 'int16', np.int16, "NIFTI_TYPE_INT16"),
                        (8, 'int32', np.int32, "NIFTI_TYPE_INT32"),
                        (16, 'float32', np.float32, "NIFTI_TYPE_FLOAT32"),
                        (32, 'complex64', np.complex64, "NIFTI_TYPE_COMPLEX64"),
                        (64, 'float64', np.float64, "NIFTI_TYPE_FLOAT64"),
                        (256, 'int8', np.int8, "NIFTI_TYPE_INT8"),
                        (512, 'uint16', np.uint16, "NIFTI_TYPE_UINT16"),
                        (768, 'uint32', np.uint32, "NIFTI_TYPE_UINT32"),
                        (1024,'int64', np.int64, "NIFTI_TYPE_INT64"),
                        (1280, 'uint64', np.uint64, "NIFTI_TYPE_UINT64"),
                        (1536, 'float128', _float128t, "NIFTI_TYPE_FLOAT128"),
                        (1792, 'complex128', np.complex128, "NIFTI_TYPE_COMPLEX128"),
                        (2048, 'complex256', _complex256t, "NIFTI_TYPE_COMPLEX256"),
        :return:
        """
        if type == '':
            type = self.hdr.get_data_dtype()

        if type == 'minimize' or type == 'minimize_int':
            from numpy import nanmax, nanmin
            # compute max value in the image and choose the best pixel type to represent all the pixels within smallest memory space
            # warning: does not take intensity resolution into account, neither complex voxels
            max_vox = nanmax(self.data)
            min_vox = nanmin(self.data)

            # check if voxel values are real or integer
            isInteger = True
            if type == 'minimize':
                for vox in self.data.flatten():
                    if int(vox) != vox:
                        isInteger = False
                        break

            if isInteger:
                from numpy import iinfo, uint8, uint16, uint32, uint64
                if min_vox >= 0:  # unsigned
                    if max_vox <= iinfo(uint8).max:
                        type = 'uint8'
                    elif max_vox <= iinfo(uint16):
                        type = 'uint16'
                    elif max_vox <= iinfo(uint32).max:
                        type = 'uint32'
                    elif max_vox <= iinfo(uint64).max:
                        type = 'uint64'
                    else:
                        raise ValueError("Maximum value of the image is to big to be represented.")
                else:
                    if max_vox <= iinfo(int8).max and min_vox >= iinfo(int8).min:
                        type = 'int8'
                    elif max_vox <= iinfo(int16).max and min_vox >= iinfo(int16).min:
                        type = 'int16'
                    elif max_vox <= iinfo(int32).max and min_vox >= iinfo(int32).min:
                        type = 'int32'
                    elif max_vox <= iinfo(int64).max and min_vox >= iinfo(int64).min:
                        type = 'int64'
                    else:
                        raise ValueError("Maximum value of the image is to big to be represented.")
            else:
                from numpy import finfo, float32, float64
                # if max_vox <= np.finfo(np.float16).max and min_vox >= np.finfo(np.float16).min:
                #    type = 'np.float16' # not supported by nibabel
                if max_vox <= finfo(float32).max and min_vox >= finfo(float32).min:
                    type = 'float32'
                elif max_vox <= finfo(float64).max and min_vox >= finfo(float64).min:
                    type = 'float64'

        # print "The image has been set to "+type+" (previously "+str(self.hdr.get_data_dtype())+")"
        # change type of data in both numpy array and nifti header
        type_build = eval(type)
        self.data = type_build(self.data)
        self.hdr.set_data_dtype(type)

Example 34

Project: numba Source File: test_array_reductions.py
def array_nanmax(arr):
    return np.nanmax(arr)

Example 35

Project: paegan Source File: gridvar.py
Function: get_xmax
    def get_xmax(self):
        return np.nanmax(np.nanmax(self._xarray))

Example 36

Project: paegan Source File: gridvar.py
Function: get_ymax
    def get_ymax(self):
        return np.nanmax(np.nanmax(self._yarray))