def _plot(self): ## pylab.clf() ## ## Added garbage collection since matplotlib objects seem to hang ## ## around and accumulate. ## import gc ## gc.collect() mesh = self.vars[0].mesh x, y = mesh.cellCenters z = self.vars[0].value xmin, ymin = mesh.extents['min'] xmax, ymax = mesh.extents['max'] from matplotlib.mlab import griddata xi = numerix.linspace(xmin, xmax, 1000) yi = numerix.linspace(ymin, ymax, 1000) # grid the data. zi = griddata(x, y, z, xi, yi, interp='linear') if hasattr(self, "_contourSet"): for collection in self._contourSet.collections: try: ix = self.axes.collections.index(collection) except ValueError, e: ix = None if ix is not None: del self.axes.collections[ix]
def _plot(self): ## plt.clf() ## ## Added garbage collection since matplotlib objects seem to hang ## ## around and accumulate. ## import gc ## gc.collect() mesh = self.vars[0].mesh x, y = mesh.cellCenters z = self.vars[0].value xmin, ymin = mesh.extents['min'] xmax, ymax = mesh.extents['max'] from matplotlib.mlab import griddata xi = numerix.linspace(xmin, xmax, 1000) yi = numerix.linspace(ymin, ymax, 1000) # grid the data. zi = griddata(x, y, z, xi, yi, interp='linear') if hasattr(self, "_contourSet"): for collection in self._contourSet.collections: try: ix = self.axes.collections.index(collection) except ValueError as e: ix = None if ix is not None: del self.axes.collections[ix] zmin, zmax = self._autoscale(vars=self.vars, datamin=self._getLimit(('datamin', 'zmin')), datamax=self._getLimit(('datamax', 'zmax'))) self.norm.vmin = zmin self.norm.vmax = zmax if self.levels is not None: levels = self.levels else: levels = numerix.arange(self.number + 1) * (zmax - zmin) / self.number + zmin self._contourSet = self.axes.contour(xi, yi, zi, levels=levels, cmap=self.cmap) self.axes.set_xlim(xmin=self._getLimit('xmin'), xmax=self._getLimit('xmax')) self.axes.set_ylim(ymin=self._getLimit('ymin'), ymax=self._getLimit('ymax')) if self.colorbar is not None: self.colorbar.plot()
def test_seed_linear_from_constraints(self, params, constraints, error): seed = dict(profile='linear') if params: seed['params'] = params unit = 'km/kg' N = 10 v = ModelVariable( name='mvar', create=dict(value=3.2, unit=unit), seed=seed, constraints=constraints, ) v.domain = mock.Mock(SedimentDBLDomain) v.domain.create_var.return_value = PhysicalField([34] * N, unit) v.domain.mesh = mock.Mock() v.domain.idx_surface = mock.Mock() v.constrain = mock.Mock() if error: with pytest.raises(error): v.setup() else: v.setup() if params is None: params = {} if constraints is None: constraints = {} startval = PhysicalField( params.get('start', constraints.get('top')), unit).inUnitsOf(unit).value stopval = PhysicalField( params.get('stop', constraints.get('bottom')), unit).inUnitsOf(unit).value expected = PhysicalField(numerix.linspace(startval, stopval, N), unit) assert numerix.array_equal(v.var, expected)
def _plot(self): from scipy.interpolate import griddata var = self.vars[0] mesh = var.mesh xmin, ymin = mesh.extents['min'] xmax, ymax = mesh.extents['max'] N = 100 X = numerix.linspace(xmin, xmax, N) Y = numerix.linspace(ymin, ymax, N) grid_x, grid_y = numerix.mgrid[xmin:xmax:N * 1j, ymin:ymax:N * 1j] if isinstance(var, FaceVariable): C = mesh.faceCenters elif isinstance(var, CellVariable): C = mesh.cellCenters U = griddata(C.value.T, var.value[0], (grid_x, grid_y), method='cubic') V = griddata(C.value.T, var.value[1], (grid_x, grid_y), method='cubic') lw = self.linewidth if isinstance(lw, (FaceVariable, CellVariable)): lw = griddata(C.value.T, lw.value, (grid_x, grid_y), method='cubic') color = self.color if isinstance(color, (FaceVariable, CellVariable)): color = griddata(C.value.T, color.value, (grid_x, grid_y), method='cubic', fill_value=color.min()) U = U.T V = V.T ang = numerix.arctan2(V, U) mag = numerix.sqrt(U**2 + V**2) datamin, datamax = self._autoscale(vars=(mag, ), datamin=self._getLimit('datamin'), datamax=self._getLimit('datamax')) mag = numerix.where(mag > datamax, numerix.nan, mag) mag = numerix.where(mag < datamin, numerix.nan, mag) if self.log: mag = numerix.log10(mag) U = mag * numerix.cos(ang) V = mag * numerix.sin(ang) # if self._stream is not None: # # the following doesn't work, nor does it help to `add_collection` first # # self._stream.arrows.remove() # self._stream.lines.remove() self.axes.cla() self._stream = self.axes.streamplot(X, Y, U, V, linewidth=lw, color=color, **self.kwargs) self.axes.set_xlim(xmin=self._getLimit('xmin'), xmax=self._getLimit('xmax')) self.axes.set_ylim(ymin=self._getLimit('ymin'), ymax=self._getLimit('ymax'))
pl = pb.MappedPlant() #pb.MappedRootSystem() #pb.MappedPlant() path = "../../../modelparameter/plant/" #"../../../modelparameter/rootsystem/" name = "manyleaves" # "oneroot" #"Anagallis_femina_Leitner_2010" # Zea_mays_1_Leitner_2010 pl.readParameters(path + name + ".xml") """ soil """ min_ = np.array([-5, -5, -15]) max_ = np.array([9, 4, 0]) res_ = np.array([5, 5, 5]) pl.setRectangularGrid(pb.Vector3d(min_), pb.Vector3d(max_), pb.Vector3d(res_), True) # cut and map segments pl.initialize() pl.simulate(14, False) phl = PhloemFluxPython(pl) segs = pl.getPolylines() #segments regrouped per organ phl.An = np.linspace(60000., 1000000., len(phl.get_segments_index(4))) phl.mp2mesh(segs) #creates grid ###################### #mesh = Grid2D(nx = len(phl.mesh.length),ny = 1, dx = phl.mesh.length, dy = np.mean(phl.mesh.cellVolumes/phl.mesh.length)) #tip indexes tiproots, tipstem, tipleaf = phl.get_organ_nodes_tips() tiproots_newID = np.array([phl.old2newNodeID[xi] for xi in tiproots]).flatten() tiproots = [np.any([tiproots_newID == yi]) for yi in phl.mesh.faceVertexIDs[0]] tiprootsfaces = sum([phl.mesh.faceVertexIDs[0] == xi for xi in tiproots_newID]) tiprootsfacesID = np.where(tiprootsfaces)[0] tiprootscells = sum([phl.mesh.cellFaceIDs[1] == xi for xi in tiprootsfaces]) tiprootscellsID = np.where(tiprootscells)[0] ####
number_of_cells = msize[1] print('Total number of cells = ' + str(number_of_cells)) # ### Loading phi values from a saved file rho_value = get_rho_tuple( number_of_cells) # get phi values from a previous .vtk file rho = CellVariable(name=r"$\Rho$", mesh=mesh, value=rho_value) ########################################################################## # Check from here # ########################################################################## nth = 91 nphi = 181 theta = numerix.linspace(0, numerix.pi, nth) phi = numerix.linspace(0, 2 * numerix.pi, nphi) probability = np.zeros(nth * nphi) conv_fac = (180.0 / numerix.pi) #file = open("Probability_output_element.txt","w") i = 0 probability = [] for iphi in range(len(phi) - 1): for ith in range(len(theta) - 1): print('----------------------------------------------------------') print(i) print('Phi = ' + str(phi[iphi] * conv_fac) + ' to ' + str(phi[iphi + 1] * conv_fac)) print('Theta = ' + str(theta[ith] * conv_fac) + ' to ' +
def seed(self, profile, **kwargs): """ Seed the value of the variable based on the profile and parameters Available profiles are: * "normal" * normal distribution of values from :data:`scipy.stats.norm` * `loc` and `scale` in units compatible with domain mesh * `coeff` to multiply the distribution with, in units compatible with that of :attr:`.var` * the normal distribution is created to have unit height for different `loc` and `scale` values * "linear" * uses :func:`~numpy.linspace` to fill the first dimension of :attr:`.var` * `start`: the start value given, else taken from constraint "top" * `stop`: the stop value given, else taken from constraint "bottom" * "lognormal" * lognormal distributuion from :data:`scipy.stats.lognorm` * `loc` and `scale` should be in units compatible with domain mesh * `shape` should be a float > 0 * the distribution is normalized to have max value = 1 Args: profile (str): The type of profile to use **kwargs: Parmeters for the profile Returns: None Raises: ValueError: if incompatible units encountered """ PROFILES = ('linear', 'normal', 'lognormal') if profile not in PROFILES: raise ValueError('Unknown profile {!r} not in {}'.format( profile, PROFILES)) if profile == 'normal': from scipy.stats import norm loc = kwargs['loc'] scale = kwargs['scale'] coeff = kwargs['coeff'] C = 1.0 / numerix.sqrt(2 * numerix.pi) # loc and scale should be in units of the domain mesh if hasattr(loc, 'unit'): loc_ = loc.inUnitsOf(self.domain.depths.unit).value else: loc_ = loc if hasattr(scale, 'unit'): scale_ = scale.inUnitsOf(self.domain.depths.unit).value else: scale_ = scale if hasattr(coeff, 'unit'): # check if compatible with variable unit try: c = coeff.inUnitsOf(self.var.unit) except TypeError: self.logger.error( 'Coeff {!r} not compatible with variable unit {!r}'. format(coeff, self.var.unit.name())) raise ValueError('Incompatible unit of coefficient') self.logger.info( 'Seeding with profile normal loc: {} scale: {} coeff: {}'. format(loc_, scale_, coeff)) normrv = norm(loc=loc_, scale=scale_) rvpdf = normrv.pdf(self.domain.depths) rvpdf /= rvpdf.max() val = coeff * rvpdf self.var.value = val elif profile == 'lognormal': from scipy.stats import lognorm loc = kwargs['loc'] scale = kwargs['scale'] coeff = kwargs['coeff'] lognorm_shape = kwargs.get('shape', 1.25) # loc and scale should be in units of the domain mesh if hasattr(loc, 'unit'): loc_ = loc.inUnitsOf(self.domain.depths.unit).value else: loc_ = loc if hasattr(scale, 'unit'): scale_ = scale.inUnitsOf(self.domain.depths.unit).value else: scale_ = scale if hasattr(coeff, 'unit'): # check if compatible with variable unit try: c = coeff.inUnitsOf(self.var.unit) except TypeError: self.logger.error( 'Coeff {!r} not compatible with variable unit {!r}'. format(coeff, self.var.unit.name())) raise ValueError('Incompatible unit of coefficient') self.logger.info( 'Seeding with profile lognormal loc: {} scale: {} shape: {} ' 'coeff: {}'.format(loc_, scale_, lognorm_shape, coeff)) rv = lognorm(lognorm_shape, loc=loc_, scale=scale_) rvpdf = rv.pdf(self.domain.depths) rvpdf = rvpdf / rvpdf.max() val = coeff * rvpdf self.var.value = val elif profile == 'linear': start = kwargs.get('start') stop = kwargs.get('stop') if start is None: start = self.constraints.get('top') if start is None: raise ValueError( 'Seed linear has no "start" or "top" constraint') else: start = PhysicalField(start, self.var.unit) self.logger.info('Linear seed using start as top value: ' '{}'.format(start)) if stop is None: stop = self.constraints.get('bottom') if stop is None: raise ValueError( 'Seed linear has no "stop" or "bottom" constraint') else: stop = PhysicalField(stop, self.var.unit) self.logger.info('Linear seed using stop as bottom value: ' '{}'.format(stop)) N = self.var.shape[0] if hasattr(start, 'unit'): start_ = start.inUnitsOf(self.var.unit).value else: start_ = start if hasattr(stop, 'unit'): stop_ = stop.inUnitsOf(self.var.unit).value else: stop_ = stop self.logger.info( 'Seeding with profile linear: start: {} stop: {}'.format( start_, stop_)) val = numerix.linspace(start_, stop_, N) self.var.value = val self.logger.debug('Seeded {!r} with {} profile'.format(self, profile))