def extract(self, osc, subscriber=0): col = osc[self.paramColumn.value] if self.paramIndex.value == 'All': result = copy.deepcopy(col) else: index = int(self.paramIndex.value) if len(col.dimensions) > 1: dim = col.dimensions[1] else: oldDim = col.dimensions[0] dim = DataContainer.FieldContainer(oldDim.data[index], unit=oldDim.unit, longname=oldDim.longname, shortname=oldDim.shortname) data = col.maskedData[index] result = DataContainer.FieldContainer(data.data, mask=data.mask, unit=col.unit, dimensions=[dim], longname=col.longname, shortname=col.shortname) #result.attributes = osc.attributes result.attributes = col.attributes result.seal() return result
def testParabel(self): x = numpy.array([-2, -1, 0, 1, 2], 'float') + 0.1 y = x**2 inputField = DC.FieldContainer(y, error=numpy.repeat(0.1, len(y)), dimensions=[ DC.FieldContainer( x, longname='abscissae', shortname='x') ], longname='parabel', shortname='f') error = inputField.error[slice(0, 1)] / (y[1] - 2 * y[2] + y[3])**2 error *= numpy.abs(y[2] - y[3]) + numpy.abs(y[1] - y[3]) + numpy.abs(y[1] - y[2]) expectedResult = DC.FieldContainer( numpy.array([0.0]), longname='position of the local minimum of parabel', shortname='x_0', error=error) w = EF.ExtremumFinder(None) w.paramExtremum.value = u'minima' #Retrieve result from worker result = w.locate(inputField) DC.assertEqual(result, expectedResult)
def testTableIncludingNanAndErrors(self): X, LAMB = numpy.meshgrid(numpy.linspace(-1.5, 1.5, self.n), numpy.linspace(-1.0, 1.0, self.m)) self.lambDim = LAMB[:, 0] self.xDim = numpy.linspace(-1.5, 1.5, self.n) lambField = DC.FieldContainer(self.lambDim, unit='1 V / m**3', longname='parameter', shortname=r'\lambda') xField = DC.FieldContainer(self.xDim, unit='1 m', longname='position', shortname='x') x0, curv, mask = Helpers.fixedPoints(lambField.data, kappa1=self.kappa1) fixedPoints = DC.FieldContainer( numpy.array(x0).transpose(), unit=xField.unit, dimensions=[DC.generateIndex(0, 3), lambField], longname='position of the local extrema of electric potential', shortname='x_0', attributes={'title': 'testTableIncludingNanAndErrors'}) fixedPoints.error = 0.1 * fixedPoints.data fixedPoints.seal() visualizer = self.visualizer(fixedPoints, show=False) filename = os.path.join( self.tmpdir, 'pyphant-' + DC.parseId(fixedPoints.id)[0] + '%s.%s' % (visualizer.name, outputFormat)) visualizer.figure.savefig(filename.replace(' ', ''))
def testIntersectionXVector(self): X, LAMB = numpy.meshgrid(numpy.linspace(-1.5, 1.5, self.n), numpy.linspace(-1.0, 1.0, self.m)) self.lambDim = LAMB[:, 0] self.xDim = numpy.linspace(-1.5, 1.5, self.n) lambField = DC.FieldContainer(self.lambDim, unit='1 V / m**3', longname='parameter', shortname=r'\lambda') xField = DC.FieldContainer(self.xDim, unit='1 m', longname='position', shortname='x') #Prepare potential V = [] for i in xrange(len(lambField.data)): u = X[i] V.append(-lambField.data[i] / 2 * u**2 + u**4 / 4 - u * self.kappa1) self.V = DC.FieldContainer( numpy.array(V), unit='1 V', dimensions=[lambField, xField], longname='electric potential', shortname=r'\varphi', attributes={'title': 'testIntersectionXVector'}) self.V.seal() visualizer = self.visualizer(self.V, show=False) filename = os.path.join( self.tmpdir, 'pyphant-' + DC.parseId(self.V.id)[0] + '%s.%s' % (visualizer.name, outputFormat)) visualizer.figure.savefig(filename.replace(' ', ''))
def setUp(self): self.n = 100 self.m = 10 self.kappa1 = 0.0 self.errLevelPos = 6 self.errLevelCurv = 5 self.x = numpy.linspace(-1.5, 1.5, self.n) self.lamb = numpy.linspace(-1.0, 1.0, self.m) X, LAMB = scipy.meshgrid(self.x, self.lamb) lambField = DC.FieldContainer(LAMB, unit='1 V / m**3', longname='parameter', shortname='\lambda') xField = DC.FieldContainer(X[0], unit='1 m', longname='position', shortname='x') V = [] for i in xrange(len(lambField.data)): u = xField.data V.append(-lambField.data[i] / 2 * u**2 + u**4 / 4 - u * self.kappa1) self.I = DC.FieldContainer(numpy.array(V), longname='intensity', shortname='I') self.I.dimensions[-1] = xField self.I0 = DC.FieldContainer(numpy.ones(self.I.data.shape, 'float'), longname='white reference', shortname='I_0') self.I0.dimensions[-1] = xField self.Id = DC.FieldContainer(numpy.zeros(self.I.data.shape, 'float'), longname='darf reference', shortname='I_d') self.Id.dimensions[-1] = xField self.sampleC = DC.SampleContainer([self.I, self.I0, self.Id])
def reshapeField(field): if field.isIndependent() or len(field.dimensions) == 1: return field dimData = [numpy.unique(d.data) for d in field.dimensions] dimDicts = [ dict([(data, index) for index, data in enumerate(dimdata)]) for dimdata in dimData ] fieldData = numpy.ones([len(d) for d in dimData]) * numpy.nan indicess = zip(*[map(lambda x: dimDicts[index][x], dim.data) \ for index, dim in enumerate(field.dimensions)]) for datum, indices in zip(field.data, indicess): fieldData[indices] = datum newDims = [ DataContainer.FieldContainer(dimData[i], f.unit, longname=f.longname, shortname=f.shortname, attributes=f.attributes) for i, f in enumerate(field.dimensions) ] newField = DataContainer.FieldContainer(fieldData, field.unit, mask=numpy.isnan(fieldData), dimensions=newDims, longname=field.longname, shortname=field.shortname, attributes=field.attributes) return newField
def calculateHistogram(self, vector, subscriber=0): bins = self.paramBins.value assert bins >= 2 # numpy 1.3 try: histo = numpy.histogram(vector.data.flat, bins, new=True, range=(numpy.floor(vector.data.min()), numpy.ceil(vector.data.max()))) # newer numpy versions except TypeError: histo = numpy.histogram(vector.data.flat, bins, range=(numpy.floor(vector.data.min()), numpy.ceil(vector.data.max()))) binCenters = histo[1][:-1] + (numpy.diff(histo[1]) / 2.0) assert len(binCenters) == bins == len(histo[0]) xdim = DataContainer.FieldContainer(binCenters, vector.unit, longname=vector.longname, shortname=vector.shortname) result = DataContainer.FieldContainer(histo[0], dimensions=[xdim], longname=u"Histogram of %s" % vector.longname, shortname=u"h") result.seal() return result
def loadImageAsGreyScale(self, subscriber=0): im = PIL.Image.open(self.paramFilename.value) if im.mode == "I;16": im = im.convert("I") data = scipy.misc.fromimage(im).astype("int16") else: data = scipy.misc.fromimage(im, flatten=True) Ny, Nx = data.shape xUnit = parseFCUnit(self.paramXScale.value) xAxis = DataContainer.FieldContainer( scipy.linspace(0.0, self._getScalar(xUnit), Nx, True), xUnit / self._getScalar(xUnit), longname='x-coordinate', shortname='x' ) if self.paramYScale.value == 'link2X': yUnit = xUnit * float(Ny) / Nx else: yUnit = parseFCUnit(self.paramYScale.value) yAxis = DataContainer.FieldContainer( scipy.linspace(0.0, self._getScalar(yUnit), Ny, True), yUnit / self._getScalar(yUnit), longname='y-coordinate', shortname='y' ) fieldUnit = parseFCUnit(self.paramFieldUnit.value) result = DataContainer.FieldContainer( data, fieldUnit, longname="Image", shortname="I", dimensions=[yAxis, xAxis] ) result.seal() return result
def testDistanceMappingCross(self): """ All elements of a cross-like feature, which span across the whole domain, are dx and dy for the vertical and the horizontal bar, respectively. The central element has distance 3dx if dy>=7**0.5, otherwise it is (dx**2+dy**2)**0.5. """ smallDim = DataContainer.FieldContainer(numpy.linspace( 0, 8**0.5, self.dim), unit='1m', longname='height', shortname='h') for yDim in [self.yDim, smallDim]: referenceField = DataContainer.FieldContainer( stringFeature(self.dim, directions=2, distanceToBorder=self.dist), dimensions=[self.xDim, yDim], unit='1', longname='String Feature', shortname='S') referenceField.seal() result = self.worker.calculateDistanceMap(referenceField) #Compute result afoot afoot = numpy.where(referenceField.data == I.FEATURE_COLOR, 1.0, 0).astype('d') dx, dy = map(lambda dim: dim.data[1] - dim.data[0], [self.xDim, yDim]) afoot[5, :] = dy / dx if dy <= dx * 7.0**0.5: centerDist = numpy.sqrt(1.0 + (dy / dx)**2) else: centerDist = 3.0 afoot[self.dim / 2, self.dim / 2] = centerDist numpy.testing.assert_array_almost_equal(afoot, result.data)
def testDistanceMappingHorizontalString2(self): """ The inner elements of a horizontal string-like feature, which does not span the whole domain have distance dy to the background, while the tips have distance dx to the background. """ referenceField = DataContainer.FieldContainer( numpy.rot90(stringFeature(self.dim, distanceToBorder=self.dist + 1)), dimensions=[self.xDim, self.yDim], unit='1', longname='String Feature', shortname='S') referenceField.seal() result = self.worker.calculateDistanceMap(referenceField) #Compute result afoot afoot = numpy.where(referenceField.data == I.FEATURE_COLOR, self.dy, 0) afoot[5, 1] = self.dx afoot[5, 9] = self.dx afoot = DataContainer.FieldContainer(afoot, dimensions=map( copy.deepcopy, [self.xDim, self.yDim]), unit=self.xDim.unit, rescale=True) self.assertEqual(afoot, result)
def testVisualization(self): X, LAMB = numpy.meshgrid(numpy.linspace(-1.5, 1.5, self.n), numpy.linspace(-1.0, 1.0, self.m)) self.lambDim = numpy.linspace(-1.0, 1.0, self.m) self.xDim = numpy.linspace(-1.5, 1.5, self.n) lambField = DC.FieldContainer(self.lambDim, unit='1 V / m**3', longname='parameter', shortname='\lambda') xField = DC.FieldContainer(self.xDim, unit='1 m', longname='position', shortname='x') #Prepare potential V = [] for i in xrange(len(lambField.data)): u = X[i] V.append(-lambField.data[i] / 2 * u**2 + u**4 / 4 - u * self.kappa1) self.V = DC.FieldContainer(numpy.array(V), unit='1 V', dimensions=[lambField, xField], longname='electric potential', shortname=r'\varphi') self.V.seal() #Visualise result visualizer = ImageVisualizer(self.V, show=False) filename = os.path.join(self.tmpdir, 'pyphant-' + DC.parseId(self.V.id)[0] + '.pdf') visualizer.figure.savefig(filename)
def testParabelArray(self): x = numpy.array([-2,-1,0,1,2],'float') field = numpy.array([(x-0.2)**2-0.5,(x+0.1)**2]) inputField = DC.FieldContainer(field, error=numpy.resize(numpy.repeat(0.1,len(field)),field.shape), dimensions=[DC.FieldContainer(numpy.array([1,2]), longname='type',shortname=r'\theta'), DC.FieldContainer(x,longname='position',shortname='x')], longname='parabel', shortname='f') def error(y): error = inputField.error[0,0] / (y[1]-2*y[2]+y[3])**2 error *= numpy.abs(y[2]-y[3]) + numpy.abs(y[1]-y[3]) + numpy.abs(y[1]-y[2]) return error expectedResult = DC.FieldContainer(numpy.array([[0.2,-0.1]]), longname = 'position of the local minima of parabel', shortname = 'x_0', error = numpy.array([[error(field[0]),error(field[1])]])) expectedResult.dimensions[-1] = DC.FieldContainer(numpy.array([1,2]), longname='type', shortname=r'\theta') w = EF.ExtremumFinder(None) w.paramExtremum.value=u'minima' #Retrieve result from worker result = w.locate(inputField) DC.assertEqual(result,expectedResult)
def testDistanceMappingInvertedStringDyDx(self): """ Consider two features, which are divided by a vertical line. The respective distances increase by dx for each column counted from the centre line. """ self.dydx = 0.01 self.yDim = DataContainer.FieldContainer(numpy.linspace( -self.dydx, self.dydx, self.dim), unit='1m', longname='height', shortname='h') referenceField = DataContainer.FieldContainer( numpy.logical_not(stringFeature(self.dim, distanceToBorder=0)), dimensions=[self.xDim, self.yDim], unit='1', longname='Inverted String Feature', shortname='S') referenceField.seal() result = self.worker.calculateDistanceMap(referenceField) #Compute result afoot afoot = numpy.zeros(referenceField.data.shape, 'f') dx = numpy.diff(referenceField.dimensions[0].data)[0] for i in xrange(referenceField.data.shape[1]): afoot[:, i] = dx * abs(5 - i) afootC = DataContainer.FieldContainer(afoot, unit=self.xDim.unit, dimensions=map( copy.deepcopy, referenceField.dimensions)) DataContainer.assertEqual(afootC, result)
def testDistanceMappingNyMuchGreaterThanNxDxDy(self): """ Consider two features, which are divided by a horizonzal line. The respective distances increase by dy for each row counted from the centre line. """ pos = 50 Nx = 101 featureField = numpy.zeros((Nx, 11)) featureField[:, :] = I.FEATURE_COLOR featureField[pos, :] = I.BACKGROUND_COLOR xDim = DataContainer.FieldContainer(numpy.linspace(-1, 1, Nx), unit='1m', longname='width', shortname='w') referenceField = DataContainer.FieldContainer( featureField, dimensions=[xDim, self.yDim], unit='1', longname='Inverted String Feature', shortname='S') referenceField.seal() result = self.worker.calculateDistanceMap(referenceField) #Compute result afoot afoot = numpy.zeros(referenceField.data.shape, 'f') dy = numpy.diff(referenceField.dimensions[1].data)[0] for i in xrange(referenceField.data.shape[0]): afoot[i, :] = dy * abs(pos - i) afoot = DataContainer.FieldContainer(afoot, unit=self.xDim.unit, dimensions=map( copy.deepcopy, referenceField.dimensions)) self.assertEqual(afoot, result)
def loadImageAsGreyScale(self, subscriber=0): im = Image.open(self.paramFilename.value) if im.mode == "I;16": im = im.convert("I") data = scipy.misc.fromimage(im).astype("int16") else: data = scipy.misc.fromimage(im, flatten=True) Ny, Nx = data.shape xUnit = Quantity(self.paramXScale.value.encode('utf-8')) xAxis = DataContainer.FieldContainer(scipy.linspace(0.0, xUnit.value, Nx, True), xUnit / xUnit.value, longname = 'x-coordinate', shortname = 'x') if self.paramYScale.value == 'link2X': yUnit = xUnit * float(Ny) / Nx else: yUnit = Quantity(self.paramYScale.value.encode('utf-8')) yAxis = DataContainer.FieldContainer(scipy.linspace(0.0, yUnit.value, Ny, True), yUnit / yUnit.value, longname = 'y-coordinate', shortname = 'y') try: FieldUnit = Quantity(self.paramFieldUnit.value.encode('utf-8')) except AttributeError: FieldUnit = self.paramFieldUnit.value result = DataContainer.FieldContainer(data, FieldUnit, longname="Image", shortname="I", dimensions=[yAxis, xAxis]) result.seal() return result
def createFieldContainer(key, array): def longname2unit(name): reg = re.compile(r"\[([^]]*)\]") m = reg.search(name) if not m or m.group(1) == "counts" or m.group(1) == "": return 1.0 else: return quantities.Quantity('1 ' + str(m.group(1))) fieldUnit = longname2unit(key) if quantities.isQuantity(fieldUnit): fieldContainer = DataContainer.FieldContainer(numpy.array(array), unit=fieldUnit, longname=key) else: try: quantities = [ quantities.Quantity(string.encode('latin-1')) for string in array ] firstUnit = quantities[0].unit scaledArray = [ quant.inUnitsOf(firstUnit).value for quant in quantities ] fieldContainer = DataContainer.FieldContainer( numpy.array(scaledArray), unit='1. %s' % firstUnit.name(), longname=key) except: fieldContainer = DataContainer.FieldContainer(numpy.array(array), unit=fieldUnit, longname=key) return fieldContainer
def setUp(self): self.dim = 11 self.worker = IM.Medianiser(None) self.referenceField = DataContainer.FieldContainer( numpy.fromfunction(lambda i, j: i, [self.dim, self.dim]), longname='Linear Reference Field', shortname='R') self.referenceField.seal() self.testField = DataContainer.FieldContainer( self.referenceField.data.copy(), longname='Noisy Field with central perturbation', shortname='R_n')
def readZipFile(filename, subscriber=1): data, names = loadDataFromZip(filename, subscriber) commonAttr, variableAttr = collectAttributes(data, names) #Wrap variable attributes into FieldContainer containers = [ column2FieldContainer(longname, column) for longname, column in variableAttr.iteritems() ] #Process SampleContainers of parsed FMF files and skip independent #variables, which are used as dimensions. fieldData, dependencies, units, shortnames = unpackAndCollateFields( variableAttr, data) independentFieldsNames = [] for fieldName, dependency in dependencies.iteritems(): if dependencies[fieldName] == []: independentFieldsNames.append(fieldName) for fieldName in independentFieldsNames: del dependencies[fieldName] #Build independent fields independentFields = {} for indepField in independentFieldsNames: indepData = checkAndCondense(fieldData[indepField]) independentFields[indepField] = DataContainer.FieldContainer( numpy.array(indepData), longname=indepField, shortname=shortnames[indepField], unit=units[indepField], rescale=True) #Build dependent fields #QUESTION: Can a field depend on a dependent field? for field, dependency in dependencies.iteritems(): newField = DataContainer.FieldContainer(numpy.array(fieldData[field]), longname=field, shortname=shortnames[field], unit=units[field], rescale=True) for i, indepField in enumerate(dependency): dim = len(newField.dimensions) - i - 1 newField.dimensions[dim] = independentFields[indepField] assert newField.isValid() containers.append(newField) #The next lines are a hack and should be dealt with properly... if u'creator' in commonAttr.keys(): creator = commonAttr[u'creator'] del commonAttr[u'creator'] result = DataContainer.SampleContainer(containers, attributes=commonAttr) result.creator = creator else: result = DataContainer.SampleContainer(containers, attributes=commonAttr) return result
def setUp(self): self.n = 1000 self.u = numpy.linspace(-1.5,1.5,self.n) self.LAMBDA = 0.5 self.kappa1=0.0 self.xField = DC.FieldContainer(self.u, unit = '1 m', longname = 'position', shortname = 'x') self.V = DC.FieldContainer(-self.LAMBDA/2* self.u**2 + self.u**4/4-self.u*self.kappa1, unit='1 V',dimensions=[self.xField], longname = 'electric potential', shortname=r'\varphi')
def testRoots(self): """ Test the correct computation of all local extrema for a bistable potential. """ #Prepare dimensions self.prepareDimensions() lambField = DC.FieldContainer( self.lambDim, unit='1 V / m**3', longname='parameter', shortname='\lambda' ) xField = DC.FieldContainer( self.xDim[0], unit='1 m', longname='position', shortname='x' ) #Prepare potential V = [] for i in xrange(len(lambField.data)): u = xField.data V.append( -lambField.data[i] / 2 * u ** 2 + u ** 4 / 4 - u * self.kappa1 ) self.V = DC.FieldContainer( numpy.array(V), unit='1 V', dimensions=[lambField, xField], longname = 'electric potential', shortname = r'\varphi' ) #Predict result x0, curv, mask = fixedPoints(lambField.data, kappa1=self.kappa1) x0 = numpy.where(curv > 0, x0, numpy.NaN) data = x0[:, ::2] dims = [DC.generateIndex(0, 2), lambField] expectedResult = DC.FieldContainer( data.transpose(), unit=xField.unit, mask=numpy.isnan(data).transpose(), dimensions=dims, longname='position of the local extrema of electric potential', shortname='x_0' ) #Configure worker w = MRA.MRA(None) w.paramScale.value = "1.0m" #Retrieve result from worker result = copy.deepcopy(w.mra(self.V))['x_{min}'] result.error=None self.test(result,expectedResult,1e-2,1e-2)
def setUp(self): self.dim = dim self.worker = S.Histogram(None) self.accuracyLevel = -3 self.uniform = DataContainer.FieldContainer(uniformSample, unit='1 V', longname='Uniform noise', shortname='g') self.norm = DataContainer.FieldContainer( normalSample, unit='1 V', longname='Gaussian white noise', shortname='w') self.uniform.seal()
def testDistanceMappRescale(self): """ The dimension of the distance map has to be a rescaled version of the original dimensions. """ dimLength = 10 * self.dim referenceField = DataContainer.FieldContainer( stringFeature(dimLength), dimensions=[ makeDim('width', '$w$', dimLength, dimUnit='1000nm'), makeDim('height', '$h$', dimLength, dimUnit='1000nm') ], unit='1V', longname='String Feature', shortname='S') referenceField.seal() result = self.worker.calculateDistanceMap(referenceField) for dim in [0, 1]: axisUnit = result.dimensions[dim].unit self.assertEqual( axisUnit.unit.name(), 'mum', 'Unit of distance should me mum but is %s.' % axisUnit.unit.name()) self.failUnless( result.unit.unit.name() == 'nm', 'Unit of distance map has to be choosen appropriately.')
def setUp(self): self.dim = 11 self.worker = IM.ApplyMask(None) self.inputField = DataContainer.FieldContainer( numpy.fromfunction(lambda i, j: i, [self.dim, self.dim]) + 100, unit='1 V/m', longname='Linear Reference Field', shortname='R') self.inputField.seal() self.mask = DataContainer.FieldContainer(TDM.stringFeature(self.dim), unit='1', longname='String Feature', shortname='S') self.mask.data[self.dim - 1, self.dim - 1] = I.FEATURE_COLOR self.mask.seal()
def fit_background(self, image, subscriber=0): poldegree = int(self.paramPoldegree.value) swidth = int(self.paramSwidth.value) sheight = int(self.paramSheight.value) threshold = int(self.paramThreshold.value) mediansize = int(self.paramMediansize.value) medianruns = int(self.paramMedianruns.value) darksize = int(self.paramDarksize.value) darkruns = int(self.paramDarkruns.value) brightsize = int(self.paramBrightsize.value) brightruns = int(self.paramBrightruns.value) dopreview = self.paramDopreview.value data = image.data #Median: for run in xrange(medianruns): data = ndimage.median_filter(data, size=mediansize) #Suspend dark spots: for run in xrange(darkruns): data = 255 - ndimage.grey_erosion(255 - data, size=darksize) #Suspend features: for run in xrange(brightruns): data = ndimage.grey_erosion(data, size=brightsize) #Fit background: if not dopreview: data = self.fit(data, poldegree, swidth, sheight, threshold) longname = "FitBackground" result = DataContainer.FieldContainer(data, copy.deepcopy(image.unit), copy.deepcopy(image.error), copy.deepcopy(image.mask), copy.deepcopy(image.dimensions), longname, image.shortname, copy.deepcopy(image.attributes), False) result.seal() return result
def threshold(self, image, subscriber=0): th = float(self.paramThreshold.value) if self.paramUnit.value.lower() != 'ignore': from pyphant.quantities import Quantity, isQuantity try: unit = float(self.paramUnit.value) assert not isQuantity(image.unit) except ValueError: try: unit = Quantity(self.paramUnit.value) except TypeError: unit = Quantity(1.0, self.paramUnit.value) assert isQuantity(image.unit) assert unit.isCompatible(image.unit.unit) th *= unit / image.unit resultArray = scipy.where(image.data < th, ImageProcessing.FEATURE_COLOR, ImageProcessing.BACKGROUND_COLOR) result = DataContainer.FieldContainer(resultArray, dimensions=copy.deepcopy( image.dimensions), longname=u"Binary Image", shortname=u"B") result.seal() return result
def testDistanceMappingBroadCross(self): """ Considering a cross, which is composed from two rectangular feature each having a smallest edge length of three, all outer elements have distance one to the background, while the inner elements have distance two to the background and the elements of the innermost 3x3 square are the roots of [[[2,m,2],[m,8,m],[2,m,2]] with m = (\sqrt(2)+1)^2. """ referenceField = DataContainer.FieldContainer( stringFeature(self.dim, width=3, directions=2, distanceToBorder=self.dist), unit='1', longname='String Feature', shortname='S') referenceField.seal() result = self.worker.calculateDistanceMap(referenceField) afoot = numpy.where(referenceField.data == I.FEATURE_COLOR, 1.0, 0) innerCross = stringFeature(self.dim, directions=2, distanceToBorder=self.innerDist) #Compute result afoot afoot = numpy.where(innerCross == I.FEATURE_COLOR, 2.0, afoot).astype('d') left = self.dim / 2 - 1 right = self.dim / 2 + 2 middle = (2.0**0.5 + 1)**2 core = numpy.sqrt( numpy.array([[2, middle, 2], [middle, 8, middle], [2, middle, 2]])) afoot[left:right, left:right] = core numpy.testing.assert_array_equal(afoot, result.data)
def testDistanceMappUnit(self): """ The dimension of the distance map has to be compatible with the dimensions of the axis. But usually it should be smaller by several orders of magnitude. """ dimLength = 10 * self.dim referenceField = DataContainer.FieldContainer( stringFeature(dimLength), dimensions=[ makeDim('width', '$w$', dimLength), makeDim('height', '$h$', dimLength) ], unit='1V', longname='String Feature', shortname='S') referenceField.seal() result = self.worker.calculateDistanceMap(referenceField) for dim in [0, 1]: axisUnit = result.dimensions[dim].unit self.failUnless( result.unit.unit.isCompatible(axisUnit.unit), 'Unit of distance map has to be compatible with unit of axis.') self.failUnless( result.unit.unit.name() == 'nm', 'Unit of distance map has to be choosen appropriately.')
def smooth(self, osc, subscriber=0): s = float(self.paramSmoothing.value) xDim = osc.dimensions[-1] x = xDim.data smoothedData = [] count = osc.data.shape[0] for i in xrange(count): y = osc.data[i] if osc.error != None: error = copy.deepcopy(osc.error[i]) error[error==0] = numpy.finfo(type(0.3)).eps weights = 1.0/(error**2) smoothYTCK,fp,ier,msg = scipy.interpolate.splrep(x,y,w=weights,s=s, full_output=True,task=0) else: smoothYTCK,fp,ier,msg = scipy.interpolate.splrep(x,y,s=s, full_output=True,task=0) if ier>0: _logger.warning("There was a problem in fitting: %i: %s, fp: %f" %(ier, msg, fp)) smoothY = scipy.interpolate.splev(x,smoothYTCK) smoothedData.append(smoothY) subscriber %= float(i)*100.0/float(count) sya = numpy.array(smoothedData) result = DataContainer.FieldContainer(sya, error = osc.error, unit=osc.unit, dimensions = osc.dimensions, longname=u'Smoothed %s'%osc.longname, shortname='\\widetilde{%s}'%osc.shortname) result.seal() return result
def main(): import pylab mra = MRA() N = 200 x = numpy.linspace(-2, 2, N) y = x**4 - 3 * x**2 + x z = y + scipy.random.randn(N) * 0.5 data = DataContainer.FieldContainer( z, dimensions=[DataContainer.FieldContainer(x, unit='1m')]) mra.paramScale.value = "1.0m" roots = mra.mra(data) pylab.plot(x, y, x, z) pylab.vlines(roots.data, -4, 4) pylab.vlines(roots.data + roots.error, -4, 4, linestyle='dashed') pylab.vlines(roots.data - roots.error, -4, 4, linestyle='dashed') pylab.show()
def testMinima(self): """ Test the correct computation of all local minima for a bistable potential. """ #Predict result x0, curv, mask = fixedPoints( numpy.array([self.LAMBDA]), kappa1=self.kappa1 ) expectedResult = DC.FieldContainer( numpy.extract(curv[0]>0,x0[0]), unit = self.xField.unit, longname = 'position of the local minima of electric potential', shortname = 'x_0' ) #Retrieve result from worker w = MRA.MRA(None) w.paramScale.value = "1.0m" result = w.mra(self.V) #Testing i = numpy.array(range(self.n)) index = numpy.logical_and(self.u > 0.7, self.u < 0.72) index = MRA.findMinima(self.V.data, 5) numpy.testing.assert_array_almost_equal( result[r'x_{min}'].data, expectedResult.data, 4 )