コード例 #1
0
def linear_fit():
    global Plot2
    valid = []
    vaxes = []
    for i in xrange(peak_res.size):
        if not Double.isNaN(peak_res[i]):
            valid.append(peak_res[i] * -1)
            vaxes.append(h2k2l2[i])
    if len(valid) == 0:
        slog('Error: there is no available peak.')
        return
    ds2 = Dataset(valid, axes=[vaxes])
    Plot2.set_dataset(ds2)
    ds = Plot2.ds
    if ds is None or len(ds) == 0:
        print 'Error: no curve to fit in Plot2'
        return
    for d in ds:
        if d.title == 'linear_fitting':
            Plot2.remove_dataset(d)
    d0 = ds[0]
    fitting = Fitting(LINEAR_FITTING)
    fitting.set_histogram(d0)
    if linear_slope.value == 0:
        fitting.set_param('a', 1)
    else:
        fitting.set_param('a', linear_slope.value)
    res = fitting.fit()
    res.var[:] = 0
    res.title = 'linear_fitting'
    Plot2.add_dataset(res)
    linear_slope.value = fitting.a
    print fitting.params
コード例 #2
0
    def getTableModel(self, book):
#        print "getTableModel book",book
        import java.util.Vector as Vector
        import java.util.Arrays as Arrays
        import java.util.Calendar as Calendar
        import com.infinitekind.moneydance.model.CurrencyType as CurrencyType
        import java.lang.Double as Double

        ct = book.getCurrencies()
        allCurrencies = ct.getAllCurrencies()
        data = Vector()
        today = Calendar.getInstance()
        balances = self.sumBalancesByCurrency(book) # HashMap<CurrencyType, Long>  contains no account info
        accounts = self.getCurrencyAccounts(book) # HashMap<CurrencyType, Accounts>
        self.totalBalance = 0.0
#        StockGlance75.totalBalance = 0.0
        for curr in allCurrencies:
            if not curr.getHideInUI() and curr.getCurrencyType() == CurrencyType.Type.SECURITY:
                price = self.priceOrNaN(curr, today, 0)
                price1 = self.priceOrNaN(curr, today, 1)
                price7 = self.priceOrNaN(curr, today, 7)
                price30 = self.priceOrNaN(curr, today, 30)
                price365 = self.priceOrNaN(curr, today, 365)
	      
                if not Double.isNaN(price) and (not Double.isNaN(price1) or not Double.isNaN(price7) or not Double.isNaN(price30) or not Double.isNaN(price365)):
		    entry = Vector(len(self.names))
                    bal = balances.get(curr)
                    balance = (0.0 if (bal == None) else curr.getDoubleValue(bal) * price)
# ?                    Double balance = (bal == null) ? 0.0 : curr.getDoubleValue(bal) * price;		        
                    self.totalBalance += balance
#                    StockGlance75.totalBalance += balance
                    entry.add(curr.getTickerSymbol())
                    entry.add(curr.getName())
                    entry.add(price)
                    entry.add(price - price1)
                    entry.add(balance)
                    entry.add((price - price1) / price1)
                    entry.add((price - price7) / price7)
                    entry.add((price - price30) / price30)
                    entry.add((price - price365) / price365)
                    entry.add(accounts.get(curr))
                    data.add(entry)
                    self.rowCurrencies.add(curr)
#                    StockGlance75.rowCurrencies.add(curr)
        self.data = data            
#        StockGlance75.data = data            
        return self.SGTableModel(self.data, self.columnNames, self.rowCurrencies)
コード例 #3
0
  def createChartDataSet (self, xyPoints, name='data'):

    #autoSort = 0
    #allowDuplicateXValues = 0
    
    xySeries = UnsortedXYSeries (name) #, autoSort, allowDuplicateXValues) 
    for i in range (len (xyPoints)):
      point = xyPoints [i]
      x = point.getX ()
      y = point.getY ()
      if (Double.isNaN (x) or Double.isNaN (y)):
        continue
      xySeries.add (x, y)
      self.pointNames.append (point.getName ())


    return XYSeriesCollection (xySeries)
コード例 #4
0
ファイル: MeasuresCells_.py プロジェクト: leec13/MorphoBactPy
	def __measureVelocity(self, img, name) :
		measure = "velocity"
		dico=self.__dictCells[name]
		for cellname in dico.keys() :
			roitemp=dico[cellname].getRoi(0)
			xc = self.__dictMeasures[dico[cellname]]["XC"]
			yc = self.__dictMeasures[dico[cellname]]["YC"]
			d=[]
			for i in range(len(xc)-1) :
				tempseq = [ xc[i], xc[i+1], yc[i], yc[i+1] ]
				if not any(Double.isNaN(val)==True for val in tempseq ) :
					d.append(Morph.distMorph([[1, xc[i], xc[i+1]],[1, yc[i], yc[i+1]]]))
				else : d.append(Double.NaN)
			d.append(Double.NaN)
			self.__dictMeasures[dico[cellname]][measure]=d
			del(d)					
コード例 #5
0
        def setValue(self, value):
	    import java.lang.Double as Double
	    import com.infinitekind.util.StringUtils as StringUtils
	    import java.awt.Color as Color
            if value == None:
                self.setText("")
            elif Double.isNaN(float(value)):
                setText("")
            else:
                if self.isZero(float(value)):
                    value = 0.0
                self.setText(StringUtils.formatPercentage(float(value), self.decimalSeparator) + "%")
                if float(value) < 0.0:
                    self.setForeground(Color.RED)
                else:
                    self.setForeground(Color.BLACK)
コード例 #6
0
ファイル: Gatan_Renamer.py プロジェクト: m-entrup/EFTEMj
 def __init__(self, imp):
     '''Get the metadata from the given dm3 image.
     '''
     extractor = GatanMetadataExtractor(imp)
     self.exposure = extractor.getExposure()
     self.magnification = extractor.getMagnification()
     self.mag_factor = extractor.getActualMagnification() / self.magnification
     self.mag_unit = 'x'
     if not Double.isNaN(extractor.getEnergyloss()):
         self.energyloss = extractor.getEnergyloss()
     else:
         self.energyloss = 0
     self.date = extractor.getDateAndTime()
     date_formater = SimpleDateFormat('yyyyMMdd')
     self.date_string = date_formater.format(self.date)
     self.name = extractor.getName()
     self.prop_dict = {}
コード例 #7
0
ファイル: MeasuresCells_.py プロジェクト: leec13/MorphoBactPy
	def __measurecumulDist(self, img, name) :
		measure = "cumulatedDist"
		dico=self.__dictCells[name]
		for cellname in dico.keys() :
			roitemp=dico[cellname].getRoi(0)
			xc = self.__dictMeasures[dico[cellname]]["XC"]
			yc = self.__dictMeasures[dico[cellname]]["YC"]
			d=[]
			d.append(0)
			for i in range(1,len(xc)-1) :
				tempseq = [ xc[i], xc[i+1], yc[i], yc[i+1] ]
				if not any(Double.isNaN(val)==True for val in tempseq ) :
					lastdist = Morph.distMorph([[1, xc[i], xc[i+1]],[1, yc[i], yc[i+1]]])
					d.append(d[-1]+lastdist)
				else : d.append(Double.NaN)
			d.append(Double.NaN)
			self.__dictMeasures[dico[cellname]][measure]=d
			del(d)		
コード例 #8
0
        def setValue(self, value):
	    import java.lang.Double as Double
	    import java.awt.Color as Color
            if value == None:
                self.setText("")
            elif Double.isNaN(float(value)):
                self.setText("")
            else:
                if self.isZero(float(value)):
                    value = 0.0
                if self.noDecimals:
		    # MD format functions can't print comma-separated values without a decimal point so
                    # we have to do it ourselves
                    scaledValue = float(value) * self.relativeTo.getUserRate();		  
                    self.setText(self.relativeTo.getPrefix() + " " + self.noDecimalFormatter.format(scaledValue) + self.relativeTo.getSuffix())
                else:
		    scaledValue = self.relativeTo.convertValue(self.relativeTo.getLongValue(float(value)))
                    self.setText(self.relativeTo.formatFancy(scaledValue, self.decimalSeparator))
                if float(value) < 0.0:
                    self.setForeground(Color.RED)
                else:
                    self.setForeground(Color.BLACK)
コード例 #9
0
 def getTemperatureHumiditySensor(self):
     result = grovepi.get(lambda: self.__temperatureHumiditySensor.get())
     if Double.isNaN(result.temperature) or Double.isNaN(result.humidity):
         # Read error.
         return None
     return result
コード例 #10
0
ファイル: MeasuresCells_.py プロジェクト: leec13/MorphoBactPy
		def graphbuttonPressed(event) :
			
			colors=[]
			#img=IJ.getImage()
			#nbslices=self.__img.getImageStackSize()
			nbslices=self.__maxLife

			acell=dico.values()[0]
			if self.__useTime : 
				x = acell.getListTimes()
				namex="Time sec"
			else : 
				x = range(1,nbslices+1)
				namex = "Frame"
			maxx=max(x)
			minx=min(x)
			
			#x=[i for i in range(1,nbslices+1)]
			font=Font("new", Font.BOLD, 14)
			tempname = WindowManager.getUniqueName(self.__img.getShortTitle())
			for i in range(len(self.__measures)) :
				#print "i", i, self.__measures[i]
				yarray=[]
				flag=True
				miny=10000000000
				maxy=-1000000000
				#we find the min and max values in order to set the scale.
				for cellname in self.__listcellname :	
					colors.append(dico[cellname].getColor())
					yarray.append(self.__dictMeasures[dico[cellname]][self.__measures[i]])
					#for meas in self.__dictMeasures[dico[cellname]][self.__measures[i]] :
					for meas in yarray[-1] :
						if (meas<miny) and (Double.isNaN(meas)==False) :
							miny=meas
					if max(yarray[-1])>maxy : maxy=max(yarray[-1])
				
				miny-=0.1*miny
				maxy+=0.1*maxy
				count=0.05
				
				for j in range(len(yarray)) :
					if j==0 :
						if len(self.__measures)>1 :
							plot=Plot("Plots-"+str(self.__measures[i]),namex,str(self.__measures[i]),x,yarray[j])
							
						else : 
							plot=Plot("Plot-"+tempname,namex,str(self.__measures[i]),x,yarray[j])
							
						plot.setLimits(minx,maxx,miny,maxy)
						plot.setColor(colors[j])
						plot.changeFont(font)
						plot.addLabel(0.05, count, self.__listcellname[j])
					else :
						plot.setColor(colors[j])
						plot.setLineWidth(3)
						plot.addPoints(x,yarray[j],Plot.LINE)
						plot.addLabel(0.05, count, self.__listcellname[j])

					count+=0.05
						
				plot.setColor(colors[0])
				plot.show()
				
			if len(self.__measures)>1 :
				IJ.run("Images to Stack", "name="+tempname+"-plots title=Plots- use")
コード例 #11
0
def nonlinear_fit():
    global Plot3
    valid = []
    vaxes = []
    for i in xrange(peak_res.size):
        if not Double.isNaN(peak_res[i]):
            valid.append(peak_res[i] * -1)
            vaxes.append(twod[i])
    if len(valid) == 0:
        slog('Error: there is not any available peak.')
        return
    ds3 = Dataset(valid, axes=[vaxes])
    Plot3.set_dataset(ds3)
    ds = Plot3.ds
    if len(ds) == 0:
        print 'Error: no curve to fit in Plot3'
        return
    for d in ds:
        if d.title == 'nonlinear_fit':
            Plot3.remove_dataset(d)
    d3 = ds[0]
    cur = d3 * math.pi / 180
    function = '2*asin(k1/x[0])+k2'
    fitting = UndefinedFitting(function, 'Energy')
    fitting.set_histogram(cur)
    m = 1.67492861e-027
    h = 6.626068e-034
    eV = 1.60217646e-019
    pl = 1.0e10
    l = h * pl * 100 / math.sqrt(linear_slope.value * eV * 20 * m)
#    if lambda_fit.value == 0 and s2_offset.value == 0:
#        fitting.set_param('k1', 0)
##        fitting.set_param('k2', 0)
#    else:
#        fitting.set_param('k1', lambda_fit.value)
#        fitting.set_param('k2', s2_offset.value)
    try:
        v_lmd = lmd.value
    except:
        v_lmd = 0
    fitting.set_param('k1', v_lmd)
    fitting.set_param('k2', 0)
    fitting.fitter.setResolutionMultiple(10)
#    fitting.fitter.getRawFitter().fitParameterSettings("k1").setStepSize(0.00001);
#    fitting.fitter.getRawFitter().fitParameterSettings("k2").setStepSize(0.00001);
    for i in xrange(5):
        res = fitting.fit()
        lambda_fit.value = fitting.k1
        s2_offset.value = fitting.k2 * 180 / math.pi
        fit_quality.value = fitting.fitter.getQuality()
        fitting = UndefinedFitting(function, 'Energy')
        fitting.set_histogram(cur)
        fitting.set_param('k1', lambda_fit.value)
    res.var[:] = 0
    res.title = 'nonlinear_fit'
    res = res * 180 / math.pi
    Plot3.add_dataset(res)
#    lambda_fit.value = fitting.k1
#    s2_offset.value = fitting.k2 * 180 / math.pi
#    fit_quality.value = fitting.fitter.getQuality()
    m1_new.value = math.asin(lambda_fit.value / 2 / D_space) * 180 / math.pi
    m2_new.value = 2 * m1_new.value
    slog('Chi2 = ' + str(fit_quality.value))
    slog('lambda = ' + str(lambda_fit.value))
    slog('meV = ' + str((h * pl / lambda_fit.value / m) ** 2 * m * 500 / eV))
    slog('two-theta_offset = ' + str(s2_offset.value))
コード例 #12
0
def spireMonoBeamSrc(freqx,beamRad,beamProfs,beamConst,effFreq,gamma,srcProf,array):
    """
    ========================================================================
    Implements the full beam model, convolved with a source profile,
    to generate the monochromatic beam profile and corresponding monochromatic
    beam solid angle at a given frequency.

    Inputs:
      freqx:     (float) frequency [Hz] for which monochromatic beam
                   profile and area should be calculated
      beamRad:   (array float) radius vector from the input beam profiles
      beamProfs: (dataset) PhotRadialCorrBeam object
                   [used to retrieve core beam profile]
      beamConst: (array float) constant part of beam profile for "array"
                       [passed to prevent repeated calls]
      effFreq:   (float) effective frequency [Hz] of array
      gamma:     (float) Exponent of powerlaw describing FWHM dependence
                   on frequency
      srcProf:   (array float) source density profile, corresponding to
                   radius column in beamProfs
      array:     (string) spire array ('Psw'|'Pmw'|'Plw')

    Outputs:     (list of objects)
                (float) Beam area [arcsec^2] at frequency freqx

    Calculation:
      Scales the core beam profile width as (freqx/effFreq)^gamma.
      Queries the calibration file to generate new core beam profile.
      Uses constant beam profile where it is larger than core profile.
      Multiplies by a source profile
      Integrates over radius to calculate beam area.

    Dependencies:
      herschel.ia.numeric.toolbox.interp.LinearInterpolator
      herschel.ia.numeric.toolbox.integr.TrapezoidalIntegrator
      
    2013/12/19  C. North  initial version

    """

    
    #calculate the "scaled" radius, as nu^-gamma
    radNew=beamRad*(freqx/effFreq)**-gamma
    maxRad=max(beamRad)
    nRad=len(beamRad)
    #ensure it doesn't go out of range
    radNew[radNew.where(radNew > maxRad)]=maxRad
    #get the corresponding beam profiles
    beamNew=Double1d(nRad)
    for r in range(nRad):
        beamNew[r]=beamProfs.getCoreCorrection(radNew[r],array)
    #apply the "constant" beam where appropriate
    #beamConst=beamProfs.getConstantCorrectionTable().getColumn(array).data
    isConst=beamNew.where(beamNew < beamConst)
    beamNew[isConst]=beamConst[isConst]

    #copy source Profile and multiply by beam
    beamNew = srcProf.copy().mult(beamNew,key='Src x Beam')
    beamMonoArea = beamNew.calcArea()
    
    if beamMonoArea==0:
        print 'calculated area=0'
        #try just the source
        srcArea=srcProf.calcArea(forceAnalytical=True)
        if Double.isNaN(srcArea):
            #no analytical source
            print 'Source is very small. No analytical area for source'
        else:
            print 'Source is very small. Replacing area with analytical area of source'
            beamMonoArea=srcArea


    ## THIS IS ONLY VALID FOR AREA
    ## FULL PROFILE OF CONVOLUTION REQUIRES PROPER CONVOLUTION

    #integrate to get solid angle (in arcsec^2)    
    #beamNew=beamNew * srcProf.profile
    #beamInterp=LinearInterpolator(beamRad,beamNew * 2. * PI * beamRad)
    #integrator=TrapezoidalIntegrator(0,maxRad)
    #beamMonoArea=integrator.integrate(beamInterp)

    return (beamMonoArea,beamNew.profile)