Example #1
0
 def _calc_snr(self, sig, var_sig):
     '''A helper function used by calc_snr().'''
     # pylint: disable-msg=R0201
     if not Float.isNaN(sig) and not Float.isNaN(var_sig):
         return sig / math.sqrt(var_sig)
     else:
         return Float.NaN
Example #2
0
def dictCheck(dictionary, value, subvalue, configName):
    map = LinkedHashMap()
    if type(dictionary) == dict:
        for k in dictionary.keys():
            if type(k) != str:
                raise TypeError, configName + " key [" + ` k ` + "] not a str"
            l = dictionary[k]
            if type(l) != value:
                raise TypeError, configName + " value [" + `l` + "] not a " \
                  + `value`
            if value == list or value == tuple:
                n = ArrayList()
                for m in l:
                    if type(m) != subvalue:
                        raise TypeError, configName + " value [" + `l` \
                          + "] isn't a " + `subvalue` + ": " + `m`
                    elif subvalue == int:
                        n.add(Integer(m))
                    elif subvalue == float:
                        n.add(Float(m))
                    else:
                        n.add(m)
                map.put(k, n)
            else:
                if value == int:
                    map.put(k, Integer(l))
                elif value == float:
                    map.put(k, Float(l))
                else:
                    map.put(k, l)
    else:
        raise TypeError, configName + " not a dict:" + ` dictionary `
    return map
Example #3
0
 def _calc_var_sig(self, sig, h, lnA, r):
     '''A helper function used by calc_snr().'''
     self._update_progress()
     if not Float.isNaN(r) and not Float.isNaN(lnA):
         Es = self.eloss_post
         return sig + h * calc_pow(Es, lnA, r)
     else:
         return Float.NaN
Example #4
0
 def addgroupattr(self, attrname, attrvalue, group=None, float=False):
     if float:
         if isinstance(attrvalue, (list, tuple)):
             for i in range(len(attrvalue)):
                 attrvalue[i] = Float(attrvalue[i])
         else:
             attrvalue = Float(attrvalue)
     return self.ncfile.addGroupAttribute(group, Attribute(attrname, attrvalue))
Example #5
0
 def interval(self, key, start, end):
     if isinstance(start, float):
         start_value = Float(start)
     else:
         start_value = start
     if isinstance(end, float):
         end_value = Float(end)
     else:
         end_value = end
     return self.__class__(self.pipeline.interval(key, start_value, end_value))
Example #6
0
 def _calc_var(self, lnA, r):
     '''A helper function used by calc_vars().'''
     self._update_progress()
     if not Float.isNaN(lnA) and not Float.isNaN(r):
         E1 = self.eloss_pre1
         E2 = self.eloss_pre2
         Es = self.eloss_post
         q = (Es - 0.5 * (E1 + E2)) / (E2 - E1)
         a01 = math.pow(Es / E1, -1 * r) * (q - 0.5)**2
         a02 = math.pow(Es / E2, -1 * r) * (q + 0.5)**2
         a11 = math.pow(Es / E1, -2 * r) * (q - 0.5)**2 *(q + 0.5)
         a12 = math.pow(Es / E2, -2 * r) * (q - 0.5) *(q + 0.5)**2
         return calc_pow(Es, lnA, r) * (a01 + a02 + (a11 + a12) / calc_pow(Es, lnA, r))
     else:
         return Float.NaN
Example #7
0
def putMaxRecommDose(guidelineDrug):
    doseLevelRanges = guidelineDrug.getOwnSlotValues(
        kb.getSlot("dose_level_ranges"))
    drugLabel = guidelineDrug.getOwnSlotValue(kb.getSlot("label"))
    maxRecommendedDoseLevel = guidelineDrug.getOwnSlotValue(
        kb.getSlot("max_recommended_dose_level"))
    if (maxRecommendedDoseLevel
            and maxRecommendedDoseLevel.getName() == "Medium_Dose"):
        print drugLabel + " has medium dose as the maximum recommended dose level"
    else:
        for dlr in doseLevelRanges:
            doseLevel = dlr.getOwnSlotValue(kb.getSlot("abstract_value"))
            if (doseLevel):
                if ((doseLevel.getName() == "High_Dose")
                        or (doseLevel.getName() == "High_Dose(high/low)")):
                    maxValue = dlr.getOwnSlotValue(kb.getSlot("upper_limit"))
                    if (maxValue):
                        guidelineDrug.setOwnSlotValue(
                            kb.getSlot("max_recommended_dose"),
                            Float(maxValue))
                    else:
                        print "No max value for the high dose range of " + drugLabel
                else:
                    print "No high dose level for " + drugLabel
            else:
                print "No nominal (abstract) dose level for a dose level range of " + drugLabel
Example #8
0
def setup(core, actor, buff):

    #powerup = actor.getUseTarget()
    powerupID = actor.getAttachment('LastUsedPUP')
    powerup = core.objectService.getObject(long(powerupID))
    effectName = powerup.getAttachment("effectName")
    powerValue = powerup.getAttachment("powerValue")
    effectName = effectName.replace('@stat_n:', '')
    actor.sendSystemMessage('en %s' % effectName, 0)
    actor.sendSystemMessage('pv %s' % powerValue, 0)
    buff.setDuration(Float(1800.0))
    if effectName:
        buff.setEffect1Name(effectName)
    if powerValue:
        buff.setEffect1Value(Float(powerValue))
    return
Example #9
0
def getGlobals(mod):
    mp = HashMap()
    for attrName in mod.__dict__:
        if not attrName.startswith('__'):
            attr = mod.__getattribute__(attrName)
            t = type(attr)
            if t is not list:
                if t is str:
                    mp.put(attrName, attr)
                elif t is int:
                    mp.put(attrName, Integer(attr))
                elif t is float:
                    mp.put(attrName, Float(attr))
                elif t is bool:
                    mp.put(attrName, Boolean(attr))
            else:
                arr = None
                if len(attr) > 0:
                    t = type(attr[0])
                    if t is int:
                        arr = __fillArray(attr, Integer)
                    elif t is float:
                        arr = __fillArray(attr, Float)
                    elif t is str:
                        arr = __fillArray(attr, String)
                mp.put(attrName, arr)
    return mp
Example #10
0
    def parse(self, query, field='', op='', parser=None, **attrs):
        """Return parsed lucene Query.

        :param query: query string
        :param field: default query field name, sequence of names, or boost mapping
        :param op: default query operator ('or', 'and')
        :param parser: custom PythonQueryParser class
        :param attrs: additional attributes to set on the parser
        """
        # parsers aren't thread-safe (nor slow), so create one each time
        cls = queryparser.classic.QueryParser if isinstance(field, string_types) else queryparser.classic.MultiFieldQueryParser
        args = field, self
        if isinstance(field, collections.Mapping):
            boosts = HashMap()
            for key in field:
                boosts.put(key, Float(field[key]))
            args = list(field), self, boosts
        parser = (parser or cls)(*args)
        if op:
            parser.defaultOperator = getattr(queryparser.classic.QueryParser.Operator, op.upper())
        for name, value in attrs.items():
            setattr(parser, name, value)
        if isinstance(parser, queryparser.classic.MultiFieldQueryParser):
            return parser.parse(parser, query)
        try:
            return parser.parse(query)
        finally:
            if isinstance(parser, PythonQueryParser):
                parser.finalize()
Example #11
0
def convert(value):
    "Return python object from java Object."
    if util.BytesRef.instance_(value):
        return util.BytesRef.cast_(value).utf8ToString()
    if not Number.instance_(value):
        return value.toString() if Object.instance_(value) else value
    value = Number.cast_(value)
    return value.doubleValue() if Float.instance_(value) or Double.instance_(value) else int(value.longValue())
Example #12
0
 def addgroupattr(self, attrname, attrvalue, group=None, float=False):
     '''
     Add a global attribute.
     
     :param attrname: (*string*) Attribute name.
     :param attrvalue: (*object*) Attribute value.
     :param group: None means global attribute.
     :param float: (*boolean*) Transfer data as float or not.
     '''
     if float:
         if isinstance(attrvalue, (list, tuple)):
             for i in range(len(attrvalue)):
                 attrvalue[i] = Float(attrvalue[i])
         else:
             attrvalue = Float(attrvalue)
     return self.ncfile.addGroupAttribute(group,
                                          Attribute(attrname, attrvalue))
Example #13
0
def setIncreaseDoseCeiling():
    for gd in kb.getCls("Guideline_Drug").getInstances():
        LBofHighestLevel = getLBofHighestLevel(
            collection2List(
                gd.getOwnSlotValues(kb.getSlot("dose_level_ranges"))))
        if (LBofHighestLevel):
            gd.setOwnSlotValue(kb.getSlot("increase_dose_ceiling"),
                               Float(LBofHighestLevel))
Example #14
0
def convert(value):
    """Return python object from java Object."""
    if util.BytesRef.instance_(value):
        return util.BytesRef.cast_(value).utf8ToString()
    if not Number.instance_(value):
        return value.toString() if Object.instance_(value) else value
    value = Number.cast_(value)
    return value.doubleValue() if Float.instance_(value) or Double.instance_(
        value) else int(value.longValue())
Example #15
0
 def __init__(self):
     head = 'Byte,Double,Float,Integer,Long,Short'.split(',')
     self.data = [[
         Byte(Byte.MIN_VALUE),
         Double(Double.MIN_VALUE),
         Float(Float.MIN_VALUE),
         Integer(Integer.MIN_VALUE),
         Long(Long.MIN_VALUE),
         Short(Short.MIN_VALUE)
     ],
                  [
                      Byte(Byte.MAX_VALUE),
                      Double(Double.MAX_VALUE),
                      Float(Float.MAX_VALUE),
                      Integer(Integer.MAX_VALUE),
                      Long(Long.MAX_VALUE),
                      Short(Short.MAX_VALUE)
                  ]]
     DefaultTableModel.__init__(self, self.data, head)
    def testSortWithScoreAndMaxScoreTracking(self):
        """
        Two Sort criteria to instantiate the multi/single comparators.
        """
        
        sorts = [Sort(SortField.FIELD_DOC), Sort()]
        for sort in sorts:
            q = MatchAllDocsQuery()
            tdc = TopFieldCollector.create(sort, 10, True, True,
                                           True, True)
      
            self.full.search(q, tdc)
      
            tds = tdc.topDocs()
            sds = tds.scoreDocs
            for sd in sds:
                self.assert_(not Float.isNaN_(sd.score))

            self.assert_(not Float.isNaN_(tds.getMaxScore()))
Example #17
0
def clickBtnEqual(event):
    global sb
    st = sb.toString()  # return as String
    ch = ''
    i = 0

    for c in st:
        i = i + 1
        if (c == '+' or c == '-' or c == '*' or c == '/'):
            ch = c
            break
    str = String(
        st
    )  # if we have to call the java String class method then we have st as string but we have to tell that it is String so we make the object of string and
    #pass the string then str is work as String object and we easily call the method of java string class
    s1 = str.substring(
        0, i - 1
    )  # if i=4 and + is at index 3 then we have to pass the 0 as starting  and 3 as second argument b/z it is excuding
    s2 = str.substring(i)
    v1 = Float.valueOf(
        s1
    )  # we know that the vi value is Integer type value b/z we convert from string to Integer but in python we cann't assign the vtype of variable
    v2 = Float.valueOf(s2)
    if (ch == '+'):
        result = v1 + v2
        #tf.setText(.toString(result))
    elif (ch == '-'):
        result = v1 - v2
    # tf.setText(Integer.toString(result))
    elif (ch == '*'):
        result = v1 * v2
        #tf.setText(Integer.toString(result))
    elif (ch == '/'):
        result = v1 / v2

        # we want the result in float so we import the __future__ in starting

    # now we have to set the text in textField as string and we have the value as Integer or float type
    #tf.setText()
    tf.setText(Float.toString(result))
    sb.delete(0, sb.length())
    sb.insert(0, tf.getText())
    def testSortWithScoreAndMaxScoreTrackingNoResults(self):
        """
        Two Sort criteria to instantiate the multi/single comparators.
        """

        sorts = [Sort(SortField.FIELD_DOC), Sort()]
        for sort in sorts:
            tdc = TopFieldCollector.create(sort, 10, True, True, True, True)
            tds = tdc.topDocs()
            self.assertEqual(0, tds.totalHits)
            self.assert_(Float.isNaN_(tds.getMaxScore()))
            def getValueForDoc(_self, doc):
                curDocID = values.docID()
                if doc < curDocID:
                    raise ValueError("doc=" + doc + " is before curDocID=" + curDocID)
                if doc > curDocID:
                    curDocID = values.advance(doc)

                if curDocID == doc:
                    return Float.intBitsToFloat(int(values.longValue()))
                else:
                    return 0.0
Example #20
0
 def __init__(self, data, headings):
     info = []
     df = DateFormat.getDateInstance(DateFormat.SHORT)
     for tf, date, size, f, d in data:
         info.append([
             Boolean(tf == '1'),
             df.parse(date),
             Integer(size.strip().replace(',', '')),
             Float(f),
             Double(d)
         ])
     DefaultTableModel.__init__(self, info, headings)
            def getValueForDoc(_self, doc):
                curDocID = values.docID()
                if doc < curDocID:
                    raise ValueError("doc=" + doc + " is before curDocID=" +
                                     curDocID)
                if doc > curDocID:
                    curDocID = values.advance(doc)

                if curDocID == doc:
                    return Float.intBitsToFloat(values.longValue())
                else:
                    return 0.0
Example #22
0
def putDoseCeilings(guidelineDrug):
    doseLevelRanges = guidelineDrug.getOwnSlotValues(
        kb.getSlot("dose_level_ranges"))
    drugLabel = guidelineDrug.getOwnSlotValue(kb.getSlot("label"))
    maxRecommendedDoseLevel = guidelineDrug.getOwnSlotValue(
        kb.getSlot("max_recommended_dose_level"))
    if (maxRecommendedDoseLevel):
        for dlr in doseLevelRanges:
            doseLevel = dlr.getOwnSlotValue(kb.getSlot("abstract_value"))
            if (doseLevel):
                if (doseLevel == maxRecommendedDoseLevel):
                    maxIncreaseDose = dlr.getOwnSlotValue(
                        kb.getSlot("lower_limit"))
                    if (maxIncreaseDose):
                        guidelineDrug.setOwnSlotValue(
                            kb.getSlot("increase_dose_ceiling"),
                            Float(maxIncreaseDose))
                    else:
                        print "No min dose for high dose level of " + drugLabel
                    maxValue = dlr.getOwnSlotValue(kb.getSlot("upper_limit"))
                    if (maxValue):
                        guidelineDrug.setOwnSlotValue(
                            kb.getSlot("max_recommended_dose"),
                            Float(maxValue))
                    else:
                        print "No max value for the high dose range of " + drugLabel

            else:
                print "No nominal (abstract) dose level for a dose level range of " + drugLabel
    else:
        print "No max_recommended_dose_level for " + drugLabel
    increaseDoseCeiling = guidelineDrug.getOwnSlotValue(
        kb.getSlot("increase_dose_ceiling"))
    maxDose = guidelineDrug.getOwnSlotValue(kb.getSlot("max_recommended_dose"))
    if (not (increaseDoseCeiling)):
        print "No increase dose ceiling for " + drugLabel
    if (not (maxDose)):
        print "No max dose for " + drugLabel
Example #23
0
def saveBlock(featureName, block):
    if (featureName == None) or (len(block) == 0):
        return

    # Get the first (and only) plate of this model, or create one if it doesn't exist yet.
    plate = model.getPlate(0)
    if plate == None:
        plate = API.get("ModelUtils").createPlate(model, len(block),
                                                  len(block[0]))

    for r in range(plate.getRows()):
        for c in range(plate.getColumns()):
            well = plate.getWell(r + 1, c + 1)
            featureValue = API.get("ModelUtils").newFeature(featureName, well)
            featureValue.setNumericValue(Float(float(block[r][c])))
Example #24
0
 def getResult(self):
     Dimension = self.getParameter(0).getStringValue()
     useDefaults = self.getParameter(1).value
     if Dimension == "1D":
         self.getParameter(7).setValue(Integer(-200))
         self.getParameter(8).setValue(Integer(-200))
         if useDefaults:
             Q = Vector()
             Q.addElement(Float(.0035))
             X = .0035
             for i in range(1, 117, 1):
                 X = X * 1.05
                 Y = Float(X)
                 Q.addElement(Float(X))
             return Q
         else:
             return self.getParameter(2).getValue()
     else:
         Q = Vector()
         Q.addElement(self.getParameter(3).getValue())
         Q.addElement(self.getParameter(4).getValue())
         Q.addElement(self.getParameter(5).getValue())
         Q.addElement(self.getParameter(6).getValue())
         return Q
   def sendMessage(self, oscAddress, *args):
      """
      Sends an OSC message consisting of the 'oscAddress' and corresponding 'args' to the OSC output device.
      """

      # HACK: For some reason, float OSC arguments do not work, unless they are explictly converted to Java Floats.
      #       The following list comprehension does the trick.
      from java.lang import Float
      
      # for every argument, if it is a float cast it to a Java Float, otherwise leave unchanged
      args = [Float(x) if isinstance(x, float) else x for x in args]
      
      #print "sendMessage args = ", args
      oscMessage = OSCMessage( oscAddress, args )          # create OSC message from this OSC address and arguments
      self.portOut.send(oscMessage)                        # and send it to the OSC device that's listening to us

      # remember that this OscIn has been created and is active (so that it can be stopped/terminated by JEM, if desired)
      _ActiveOscOutObjects_.append(self)
Example #26
0
def getProtonsCharge( instr, runnum):
      import os
      (nxs, prenxs) = getRunDir(instr, runnum)
     
      node = NexNode( nxs)     
      for i in range(0,node.getNChildNodes()):
       
         n = node.getChildNode( i)       
        
         if n.getNodeClass()=="NXentry":
            
            try:
               V = n.getChildNode("proton_charge").getNodeValue()
              
               F = ConvertDataTypes.floatValue(V)
               return Float(F).doubleValue()
            except:
               pass

      return Double.NaN
Example #27
0
    def __init__(self,
                 index_dir,
                 search_fields=['canonical_url', 'title', 'meta', 'content'],
                 unique_field='uq_id_str',
                 boost=dict(canonical_url=4.0,
                            title=8.0,
                            meta=2.0,
                            content=1.0),
                 date_format='%Y-%m-%dT%H:%M:%S'):
        """Constructor of Searcher.

        Parameters
        ----------
        index_dir : string
            The location of lucene index.
        search_fields : list
            A list of field names indicating fields to search on.
        unique_field : string
            The field name, on which the duplication should avoid.
        boost : dict
            This dict control the weight when computing score.
        date_format : string
            Convert the string into datetime. Should consistent with the
            index part.
        """
        self.index_dir = index_dir
        self.search_fields = search_fields
        self.sort_by_recent = Sort(
            SortField('date_published', SortField.Type.STRING, True))
        self.store = FSDirectory.open(File(index_dir))
        self.reader = DirectoryReader.open(self.store)
        self.isearcher = IndexSearcher(self.reader)
        self.analyzer = StandardAnalyzer()
        self.dup_filter = DuplicateFilter(unique_field)
        self.boost_map = HashMap()
        for k, v in boost.iteritems():
            self.boost_map.put(k, Float(v))
        self.mul_parser = MultiFieldQueryParser(search_fields, self.analyzer,
                                                self.boost_map)
        self.date_format = date_format
Example #28
0
    def getJavaValue(self, value, type):
        try:
            if type == AppilogTypes.LONG_DEF:
                return Long(value)

            if type == AppilogTypes.INTEGER_DEF:
                return Integer(value)

            if type == AppilogTypes.FLOAT_DEF:
                return Float(value)

            if type == AppilogTypes.DOUBLE_DEF:
                return Double(value)

            if type == AppilogTypes.BOOLEAN_DEF:
                return Boolean(value)
            return value
        except JavaException, ex:
            msg = ex.getMessage()
            info = logger.prepareJavaStackTrace()
            logger.debug(info)
            raise CiImportException, self.makeConversionMessage(
                'Error while converting to type %s ' % type, msg)
Example #29
0
def format_for_nan(value):
    if Float.isNaN(value) or value==-999.99:
        return "NaN"
    else:
        return "%0.2f"%value 
Example #30
0
 def calc_sig(self, sig, lnA, r):
     '''A helper function used by calc_map().'''
     if not Float.isNaN(lnA) and not Float.isNaN(r) and sig > 0:
         return float(sig) - calc_pow(self.eloss_post, lnA, r)
     else:
         return Float.NaN
def test_remove():
    assert set(
        g.E.weight) == {0.4000000059604645, 0.5, 1.0, 0.20000000298023224}
    g.E.has("weight", Float(0.5), 'lt').remove()
    assert set(g.E.weight) == {0.5, 1.0}
    assert len(g.E.weight) == 3
Example #32
0
def format_for_nan(value):
    if Float.isNaN(value) or value == -999.99:
        return "NaN"
    else:
        return "%0.2f" % value
Example #33
0
 def _calc_h(self, r, lnA, var):
     '''A helper function used by calc_hs().'''
     self._update_progress()
     Es = self.eloss_post
     if not Float.isNaN(lnA) and not Float.isNaN(r):
         return 1 + (var / calc_pow(Es, lnA, r))
Example #34
0
    d[_v] = _id

from java.lang import Long, Integer, Short, Character, Byte, Boolean, Double, Float, String
from java.math import BigInteger

values = [
    0, 0L, 0.0, 'c', "string", (), o, c, foo, subfoo, subfoo2, n, Object,
    Class, Foo, SubFoo, C, SubFoo2, N, Integer,
    Long(0),
    Integer(0),
    Short(0),
    Character('c'),
    Byte(0),
    Boolean(0),
    Double(0),
    Float(0),
    String("js"),
    BigInteger("0")
]


def pp(v):
    inst = d.get(v, None)
    if inst is not None:
        return inst
    if hasattr(v, '__name__'):
        return v.__name__
    if isinstance(v, (String, Number, Character, Boolean)):
        n = v.__class__.__name__
        return "%s[%s]" % (n[n.rfind('.') + 1:], v)
    return repr(v)
Example #35
0
import java.lang
from java.lang import Float
#print 2+2
for i in range(10):
  print str(i)
print Float.parseFloat("123.3423423")
lista=[1,2,3,4,5,6,7,8,9,10,11,12]
l=[y for y in lista if y>10]
print lista
print l
Example #36
0
tempCLImage = clij.create([inputCLImage.getWidth(),
                           inputCLImage.getHeight()],
                          inputCLImage.getNativeType())
outputCLImage = clij.create(
    [inputCLImage.getWidth(),
     inputCLImage.getHeight()], inputCLImage.getNativeType())

# crop out a center plane of the 3D data set
clij.op().copySlice(inputCLImage, tempCLImage, 64)

# apply a filter to the image using ClearCL / OpenCL
clij.execute(
    filesPath + "differenceOfGaussian.cl", "subtract_convolved_images_2d_fast",
    {
        "src": tempCLImage,
        "dst": outputCLImage,
        "radius": 6,
        "sigma_minuend": Float(1.5),
        "sigma_subtrahend": Float(3)
    })

# convert the result back to imglib2 and show it
result = clij.pull(outputCLImage)
result.show()
IJ.run("Enhance Contrast", "saturated=0.35")

# clean up
inputCLImage.close()
tempCLImage.close()
outputCLImage.close()
Example #37
0
 def getFloatPosition(self, d):
     return Float(self.pos[d])
Example #38
0
def format_for_nan(value):
    if Float.isNaN(value):
        return "NaN"
    else:
        return "%f" % value
def FindMinMax(CorrMapCV, Unique=True, MinMax="Max", Score_Threshold=0.5, Tolerance=0):
	'''
	Detect Minima(s) or Maxima(s) in the correlation map
	The function uses for that the MinMaxLoc from opencv for unique detection 
	or the MaximumFinder from ImageJ for multi-detection (in this case, for min detection the correlation map is inverted)
	
	- Unique			: True if we look for one global min/max, False if we want local ones
	- MinMax 			: "Min" if we look for Minima, "Max" if we look for maxima
	- Score_Threshold 	: in range [0;1] (correlation maps are normalised)
	- Tolerance 		: Parameters for flood-fill. Not used here so should be set to 0 
	
	Returns List of Min/Max : [(X, Y, Coefficient), ... ]
	'''
	#### Detect min/maxima of correlation map ####
	Extrema = [] 
	
	## if 1 hit expected
	if Unique: # Look for THE global min/max
		minVal = DoublePointer(1) 
		maxVal = DoublePointer(1) 
		minLoc = Point() 
		maxLoc = Point() 
		minMaxLoc(CorrMapCV, minVal, maxVal, minLoc, maxLoc, Mat())
		
		if MinMax=="Min": # For method based on difference we look at the min value 
			X = minLoc.x() 
			Y = minLoc.y()
			Coeff = minVal.get() 
	 
		elif MinMax=="Max": 
			X = maxLoc.x() 
			Y = maxLoc.y()
			Coeff = maxVal.get()
		
		# Append to the output list
		Extrema.append( (X, Y, Coeff) )
		
		
	
	## if more hit expected
	else: # expect more than 1 template/image. Do a multi minima/maxima detection
		
		## OLD CODE LEFT BUT DONT DO IT, NOT GOOD PREACTICE !! Normalise the correlation map to 0-1 (easier to apply the threshold)
		## Rather use normalised method only for the computation of the correlation map (by default normalised method are 0-1 bound)
		# The normalised method are already normalised to 0-1 but it is more work to take it into account in this function 
		# WARNING : this normalisation normalise regarding to the maxima of the given correlation map
		# Not good because it means the thresholding is define relative to a correlation map : a score of 1 might not correspond to a correlation of 1
		# But only means that the pixel was the maximum of this particular correlation map 
		
		#CorrMapNormCV = Mat()
		#normalize(CorrMapCV, CorrMapNormCV, 0, 1, NORM_MINMAX, CV_32FC1, None)

		# Visualisation for debugging
		#CorrMapNorm = MatToImProc(CorrMapNormCV)
		#CorrMapNorm = ImagePlus("Normalised", CorrMapNorm)
		#CorrMapNorm.show()

		
		
		### Maxima/Minima detection on the correlation map
		
		## Difference-based method : we look for min value. For that we detect maxima on an inverted correlation map
		if MinMax=="Min": 
			
			# Invert the correlation map : min becomes maxima
			One = Scalar(1.0)
			CorrMapInvCV = subtract(One, CorrMapCV).asMat()		
			#CorrMapInv = MatToImProc(CorrMapInvCV)
			#CorrMapInv = ImagePlus("Inverted", CorrMapInv)
			#CorrMapInv.show()
			
			
			# Apply a "TO ZERO" threshold on the correlation map : to compensate the fact that maxima finder does not have a threshold argument
			# TO ZERO : below the threshold set to 0, above left untouched
			# NB : 1-score_threshold since we have inverted the image : we want to look for minima of value <x so we have to look for maxima of value>1-x in the inverted image
			CorrMapThreshCV = Mat()
			threshold(CorrMapInvCV, CorrMapThreshCV, 1-Score_Threshold, 0, CV_THRESH_TOZERO)
			CorrMapThresh = MatToImProc(CorrMapThreshCV) # Keep this conversion, not only for visualisation
			#CorrMapThreshImp = ImagePlus("Thresholded", CorrMapThresh)
			#CorrMapThreshImp.show()
			

		
		## Correlation-based method : we look for maxima
		elif MinMax=="Max": 
			# Apply a "TO ZERO" threshold on the correlation map : to compensate the fact that maxima finder does not have a threshold argument
			# TO ZERO : below the threshold set to 0, above left untouched
			# NB : 1-score_threshold since we have inverted the image : we want to look for minima of value <x so we have to look for maxima of value>1-x in the inverted image
			CorrMapThreshCV = Mat()
			threshold(CorrMapCV, CorrMapThreshCV, Score_Threshold, 0, CV_THRESH_TOZERO)
			CorrMapThresh = MatToImProc(CorrMapThreshCV) # Keep this conversion, not only for visualisation
			#CorrMapThreshImp = ImagePlus("Thresholded", CorrMapThresh)
			#CorrMapThreshImp.show()
			
		
		
		## For both cases (Multi-Min/Max-detection) detect maxima on the thresholded map
		# Detect local maxima
		excludeOnEdge = False # otherwise miss quite a lot of them
		Polygon = MaximumFinder().getMaxima(CorrMapThresh, Tolerance, excludeOnEdge)
		
		# Maxima as list of points
		#roi = PointRoi(Polygon)
		
		# Generate Hit from max coordinates
		#print Polygon.npoints," maxima detected in this score map"
		if Polygon.npoints!=0: # Check that there are some points indeed. Otherwise Polygon.xpoints and ypoints are anyway initialised with [0,0,0,0] even if Npoints=0 !
			
			for i in range(Polygon.npoints): # dont directly loop on xpoints and ypoint since initialised with [0,0,0,0] ie less than 4 points we get some 0,0 coordinates
			
				# Get point coordinates
				X, Y = Polygon.xpoints[i], Polygon.ypoints[i]

				# Get Coeff
				Coeff = CorrMapThresh.getPixel(X, Y)
				Coeff = Float.intBitsToFloat(Coeff) # require java.lang.Float
				
				# Revert the score again if we were detecting minima initially (since found as maxima of a reverted correlation map)
				if MinMax=="Min":
					Coeff = 1-Coeff
				
				# Wrap into corresponding hit
				Extrema.append( (X, Y, Coeff) )
	
	return Extrema
imp = IJ.openImage("http://wsr.imagej.net/images/blobs.gif");
# IJ.openImage("C:/structure/data/blobs.gif");

# Init GPU
from net.haesleinhuepf.clijx import CLIJx;
clijx = CLIJx.getInstance();

# push data to GPU
inputImage = clijx.push(imp);

# blur a bit and detect maxima
from java.lang import Float;
blurred = clijx.create(inputImage);
detected_spots = clijx.create(inputImage);

clijx.op().blur(inputImage, blurred, Float(15), Float(15), Float(0));

print(str(blurred));

from java.lang import Integer;
clijx.op().detectMaximaBox(blurred, detected_spots, Integer(10));

clijx.show(detected_spots, "spots");

# convert spots image to spot list
number_of_spots = clijx.op().sumPixels(detected_spots);
pointlist = clijx.create([number_of_spots, 2]);
clijx.op().spotsToPointList(detected_spots, pointlist);

distance_matrix = clijx.create([number_of_spots, number_of_spots]);
clijx.op().generateDistanceMatrix(pointlist, pointlist, distance_matrix);
def format_for_nan(value):
    if Float.isNaN(value):
        return "NaN"
    else:
        return "%f"%value
import sys

if sys.platform.startswith('java'):
    from java.lang import String, Integer, Long, Float, Short, Double

    varz = {
        'java_string_int': String('1'),
        'java_string_float': String('1.1'),
        'java_string_hex': String('F00'),
        'java_string_embedded_base': String('0xf00'),
        'java_string_invalid': String('foobar'),
        'java_integer': Integer(1),
        'java_long': Long(1),
        'java_short': Short(1),
        'java_float': Float(1.1),
        'java_double': Double(1.1)
    }

else:
    varz = {}


class MyObject:
    def __init__(self, value):
        self.value = value

    def __int__(self):
        return 42 / self.value

    def __str__(self):
        return 'MyObject'
    def _getIndex(self, even, odd):

        mergePolicy = LogDocMergePolicy()
        mergePolicy.setMergeFactor(1000)
        directory = RAMDirectory()
        self.dirs.append(directory)

        writer = self.getWriter(directory=directory,
                                analyzer=SimpleAnalyzer(Version.LUCENE_CURRENT),
                                maxBufferedDocs=2, mergePolicy=mergePolicy)

        if self.dvStringSorted:
            # Index sorted
            stringDVType = FieldInfo.DocValuesType.SORTED
        elif self.notSorted:
            # Index non-sorted
            stringDVType = FieldInfo.DocValuesType.BINARY
        else:
            # sorted anyway
            stringDVType = FieldInfo.DocValuesType.SORTED

        ft1 = FieldType()
        ft1.setStored(True)
        ft2 = FieldType()
        ft2.setIndexed(True)

        for i in xrange(len(self.data)):
            if (i % 2 == 0 and even) or (i % 2 == 1 and odd):
                doc = Document()
                doc.add(Field("tracer", self.data[i][0], ft1))
                doc.add(TextField("contents", self.data[i][1], Field.Store.NO))
                if self.data[i][2] is not None:
                    doc.add(StringField("int", self.data[i][2], Field.Store.NO))
                    if self.supportsDocValues:
                        doc.add(NumericDocValuesField("int_dv", Long.parseLong(self.data[i][2])))
                if self.data[i][3] is not None:
                    doc.add(StringField("float", self.data[i][3], Field.Store.NO))
                    if self.supportsDocValues:
                        doc.add(FloatDocValuesField("float_dv", Float.parseFloat(self.data[i][3])))

                if self.data[i][4] is not None:
                    doc.add(StringField("string", self.data[i][4], Field.Store.NO))
                    if self.supportsDocValues:
                        if stringDVType == FieldInfo.DocValuesType.SORTED:
                            doc.add(SortedDocValuesField("string_dv", BytesRef(self.data[i][4])))
                        elif stringDVType == FieldInfo.DocValuesType.BINARY:
                            doc.add(BinaryDocValuesField("string_dv", BytesRef(self.data[i][4])))
                        else:
                            raise ValueError("unknown type " + stringDVType)

                if self.data[i][5] is not None:
                    doc.add(StringField("custom", self.data[i][5], Field.Store.NO))
                if self.data[i][6] is not None:
                    doc.add(StringField("i18n", self.data[i][6], Field.Store.NO))
                if self.data[i][7] is not None:
                    doc.add(StringField("long", self.data[i][7], Field.Store.NO))
                if self.data[i][8] is not None:
                    doc.add(StringField("double", self.data[i][8], Field.Store.NO))
                    if self.supportsDocValues:
                        doc.add(NumericDocValuesField("double_dv", Double.doubleToRawLongBits(Double.parseDouble(self.data[i][8]))))
                if self.data[i][9] is not None:
                    doc.add(StringField("short", self.data[i][9], Field.Store.NO))
                if self.data[i][10] is not None:
                    doc.add(StringField("byte", self.data[i][10], Field.Store.NO))
                if self.data[i][11] is not None:
                    doc.add(StringField("parser", self.data[i][11], Field.Store.NO))

                for f in doc.getFields():
                    if f.fieldType().indexed() and not f.fieldType().omitNorms():
                        Field.cast_(f).setBoost(2.0)

                writer.addDocument(doc)

        reader = writer.getReader()
        writer.close()

        return self.getSearcher(reader=reader)