예제 #1
0
파일: makeplots.py 프로젝트: niyaa/paper
def calculateSigmaThroughInterpolation(caseList, Re):
    '''
    Creates, through interpolation new result for a given Re
    accepts caseList for a given alfa
    '''
    S = [0.01, 0.025, 0.04, 0.055, 0.07, 0.085, 0.1, 0.115, 0.13, 0.145, 0.16, 0.175, 0.19, 0.205, 0.22, 0.235, 0.25]
    caseList.sort(key=lambda l: l.alfa)
    out=[]        
    for key, group in groupby(caseList, lambda x: x.alfa):
        alist = list(group)
    
        case=Case()
        case.alfa = alist[0].alfa
        case.Re = Re
        stab=[]
        sigma=[]
        for s in S:
#            try:
            sig=calculateSigmaForS(alist, s, Re)
            sigma.append(sig)
            stab.append(s)
#            except:
#                print "Failed for:"
#                print "Alfa=" + str(case.alfa) + " S=" + str(s)
#                continue
        case.S=stab
        case.sigma=sigma
        out.append(case)
    return out
예제 #2
0
 def onConnectionLost(self, failedByMe):
    Case.onConnectionLost(self, failedByMe)
    
    if self.behaviorClose == Case.WRONG_CODE:
       self.behavior = Case.FAILED
       self.passed = False
       self.result = self.resultClose 
예제 #3
0
 def onConnectionLost(self, failedByMe):
    Case.onConnectionLost(self, failedByMe)
    
    self.passed = True
    self.behavior = Case.INFORMATIONAL
    self.behaviorClose = Case.INFORMATIONAL
    self.result = "Actual events are undefined by the spec."
예제 #4
0
파일: engine.py 프로젝트: bbglab/wok
	def create_case(self, case_name, conf_builder, project_name, flow_name, container_name):
		"Creates a new workflow case"

		session = db.Session()
		if session.query(db.Case).filter(db.Case.name==case_name).count() > 0:
			raise Exception("A case with this name already exists: {}".format(case_name))

		flow_uri = "{}:{}".format(project_name, flow_name)

		self._log.info("Creating case {} from {} ...".format(case_name, flow_uri))

		try:
			try:
				flow = self.projects.load_flow(flow_uri)
				project = flow.project
			except:
				self._log.error("Error while loading the workflow from {}".format(flow_uri))
				raise

			for platform in self._platforms:
				try:
					platform.data.remove_case(case_name)
					platform.data.create_case(case_name)
				except:
					self._log.error("Error while initializing data for case {}".format(case_name))
					raise

			try:
				case = Case(case_name, conf_builder, project, flow, container_name, engine=self)

				self._cases += [case]
				self._cases_by_name[case_name] = case

				case.persist(session)

				session.flush()
				self.notify(lock=False)
			except:
				self._log.error("Error while creating case {} for the workflow {} with configuration {}".format(
					case_name, flow_uri, conf_builder.get_conf()))
				raise
		except:
			session.rollback()
			#self._log.error("Error while creating case {} for the workflow {} with configuration {}".format(
			#	case_name, flow_uri, conf_builder.get_conf()))
			raise

		session.close()

		self._log.debug("\n" + repr(case))

		self._lock.release()
		try:
			self.case_created.send(case)
		finally:
			self._lock.acquire()

		return SynchronizedCase(self, case)
예제 #5
0
파일: makeplots.py 프로젝트: niyaa/paper
def calcMaxSigma(caseList):
    '''
    For a given caseList (single alfa) returns a colection of Re, S, Sig
    '''
    caseList.sort(key=lambda l: l.Re)
    S = [0.01, 0.025, 0.04, 0.055, 0.07, 0.085, 0.1, 0.115, 0.13, 0.145, 0.16, 0.175, 0.19, 0.205, 0.22, 0.235, 0.25]
#    S = [0.025, 0.05, 0.075, 0.1, 0.125, 0.15, 0.175, 0.2]
    out=[]
    
    for key, group in groupby(caseList, lambda x: x.Re):
        alist = list(group)        
        s, sig = getSig_S(alist)
#        print s, sig
        i=0
        if s[0] > S[0]:
            for ss in S:
                if ss in s:
                    break
                s.insert(i, ss)
                sig.insert(i, calculateSigmaForS(caseList, ss, alist[0].Re))
                i=i+1
                
        if s[-1] < S[-1]:
            for ss in S:
                if ss not in s: continue
                if ss <= s[-1]:
                    continue
                else:
#                    print ss, alist[0].Re
                    s.insert(len(s), ss)
                    sig.insert(len(sig), calculateSigmaForS(caseList, ss, alist[0].Re))
#                    print s, sig
        
        if float(alist[0].alfa) == 3:  
            #extra manual ...
            if float(alist[0].Re) == 1900:
                ssig = calculateSigmaForS(caseList, 0.025, 1900)
                s.insert(1, 0.025)
                sig.insert(1, ssig)
#                print ssig
                
            #extra manual ...
            if float(alist[0].Re) == 1500:
                ssig = calculateSigmaForS(caseList, 0.025, 1500)
                s.insert(1, 0.025)
                sig.insert(1, ssig)
#                print ssig
                
#        print alist[0].Re, s, sig
        case=Case()
        case.alfa = alist[0].alfa
        case.Re = alist[0].Re
        case.S = s
        case.sigma = sig
        out.append(case)        
        
    return out
   def onConnectionLost(self, failedByMe):
      Case.onConnectionLost(self, failedByMe)
      
      if self.behaviorClose == Case.WRONG_CODE:
         self.behavior = Case.FAILED
         self.passed = False
         self.result = self.resultClose

      ## the close reason we sent was invalid UTF8, so we
      ## convert to HEX representation for later case reporting
      self.p.localCloseReason = binascii.b2a_hex(self.p.localCloseReason)
예제 #7
0
파일: extractdata.py 프로젝트: niyaa/paper
def linearPt(file='EnergyFile.mdl',up=1e-8, down=1e-18):
    icase=Case();
    icase.time, icase.mod, icase.energy= np.loadtxt(file,comments="\x00", skiprows=1, usecols=(0,1,2), unpack=True);
    t1=icase.time[-1];
    print(t1); 
    
    #1 get smaller than some, and not letter than some
    t0 = icase.time[(icase.mod==1) & (icase.energy<up) & (icase.energy>down) & (icase.time<t1) & (icase.time>500) ]
    e0 = icase.energy[(icase.mod==1) & (icase.energy<up) & (icase.energy>down) & (icase.time<t1) & (icase.time>500) ]
    #need some sek back from here, but not less than 300
    if len(t0) < 3:
        t0 = icase.time[(icase.mod==1) & (icase.energy<up) & (icase.energy>down) & (icase.time<t1) & (icase.time>400) ]
        e0 = icase.energy[(icase.mod==1) & (icase.energy<up) & (icase.energy>down) & (icase.time<t1) & (icase.time>400) ]
    if len(t0) < 3:
        t0 = icase.time[(icase.mod==1) & (icase.energy<up) & (icase.energy>down) & (icase.time<t1) & (icase.time>300) ]
        e0 = icase.energy[(icase.mod==1) & (icase.energy<up) & (icase.energy>down) & (icase.time<t1) & (icase.time>300) ]
    if len(t0) < 3:
        t0 = icase.time[(icase.mod==1) & (icase.energy<10*up) & (icase.energy>0.1*down) & (icase.time<t1) & (icase.time>150) ]
        e0 = icase.energy[(icase.mod==1) & (icase.energy<10*up) & (icase.energy>0.1*down) & (icase.time<t1) & (icase.time>150) ]
    if len(t0) < 3:
        t0 = icase.time[(icase.mod==1) & (icase.energy<10*up) & (icase.energy>0.1*down) & (icase.time<t1) & (icase.time>100) ]
        e0 = icase.energy[(icase.mod==1) & (icase.energy<10*up) & (icase.energy>0.1*down) & (icase.time<t1) & (icase.time>100) ]
    if len(t0) < 3:
        t0 = icase.time[(icase.mod==1) & (icase.energy<10*up) & (icase.energy>0.1*down) & (icase.time<t1) & (icase.time>50) ]
        e0 = icase.energy[(icase.mod==1) & (icase.energy<10*up) & (icase.energy>0.1*down) & (icase.time<t1) & (icase.time>50) ]
    if len(t0) < 3:
        t0 = icase.time[(icase.mod==1) & (icase.energy<10*up) & (icase.energy>0.1*down) & (icase.time<t1) & (icase.time>30) ]
        e0 = icase.energy[(icase.mod==1) & (icase.energy<10*up) & (icase.energy>0.1*down) & (icase.time<t1) & (icase.time>30) ]
    if len(t0) < 3:
        t0 = icase.time[(icase.mod==1) & (icase.energy<10*up) & (icase.energy>0.1*down) & (icase.time<t1) & (icase.time>0) ]
        e0 = icase.energy[(icase.mod==1) & (icase.energy<10*up) & (icase.energy>0.1*down) & (icase.time<t1) & (icase.time>0) ]
    if len(t0) < 3:
        t0 = icase.time[(icase.mod==1)]
        e0 = icase.energy[(icase.mod==1)]
    print icase.S, icase.Re, icase.mu, len(t0), icase.Name
    tmax = max(t0)
    tmin = min(t0)
    
    if tmax-tmin>50:
        tmin = tmax-50
    if tmax-tmin<25:
        tmin=tmax-25
    tt0=icase.time[(icase.mod==1)];
    if((tt0[-1]-tt0[-2])>1):tmin=tmax-50*(tt0[-1]-tt0[-2]);
#    
#    tmax=140
#    tmin=120
    
    t = icase.time[(icase.mod==1) & (icase.time>tmin) & (icase.time<tmax)]
    e = icase.energy[(icase.mod==1) & (icase.time>tmin) & (icase.time<tmax)]
    print(t);
    print(e);
    return (t,e)
예제 #8
0
 def onConnectionLost(self, failedByMe):
    Case.onConnectionLost(self, failedByMe)
    
    self.passed = True
    
    
    if self.behavior == Case.OK:
       self.result = "Text message was processed before close."
    elif self.behavior == Case.NON_STRICT:
       self.result = "Close was processed before text message could be returned."
    
    self.behavior = Case.INFORMATIONAL
    self.behaviorClose = Case.INFORMATIONAL
    def test_instantiation(self):
        c = Case.objects.create(animal=self.animal)
        c = Case(animal=self.animal)
        c.clean()
        c.save()

        self.assertEquals(c.animal, self.animal)

        c.animal = Animal.objects.create()
        c.clean()
        c.save()
        
        self.assertNotEquals(c.animal, self.animal)
예제 #10
0
 def onConnectionLost(self, failedByMe):
    Case.onConnectionLost(self, failedByMe)
    frames_expected = {}
    frames_expected[0] = len(self.payload) / self.p.autoFragmentSize
    frames_expected[1] = 1 if len(self.payload) % self.p.autoFragmentSize > 0 else 0
    frames_got = {}
    frames_got[0] = self.p.txFrameStats[0]
    frames_got[1] = self.p.txFrameStats[1]
    if frames_expected == frames_got:
       pass
    else:
       self.behavior = Case.FAILED
       self.result = "Frames transmitted %s does not match what we expected %s." % (str(frames_got), str(frames_expected))
 def test_yearnumbers(self):
     c = Case(animal=self.animal)
     self.assertEquals(c.current_yearnumber, None)
     c.save()
     self.assertEquals(c.current_yearnumber, None)
 
     obs = Observation.objects.create(
         animal = c.animal,
         datetime_observed= UncertainDateTime(2011),
         datetime_reported= UncertainDateTime(2011),
     )
     obs.cases.add(c)
     # update c
     c = Case.objects.get(id=c.id)
     self.assertNotEquals(c.current_yearnumber, None)
예제 #12
0
    def __init__(self, matcher):
        Console.__init__(self)
        self.config = self._default_config
        self.prompt = ">> "
        self.intro = "Welcome to the CBR system. Type 'help' for a list of commands."
        self.matcher = matcher
        if not self.matcher.cases:
            self.intro += "\nNOTE: Currently no cases loaded (you may want to run parser.py to generate some)!"

        self.query = Case()
        self.result = []
        if not sys.stdin.isatty():
            self.prompt = self.intro = ""
            self.interactive = False
            self.config['auto_run'] = False
        else:
            self.interactive = True
예제 #13
0
 def onConnectionLost(self, failedByMe):
    self.producer.stopProducing()
    Case.onConnectionLost(self, failedByMe)
예제 #14
0
def __init__(self, protocol):
    Case.__init__(self, protocol)
    self.reportTime = True
예제 #15
0
 def test_safe_case(self):
     test_case = Case(0)
     self.assertFalse(test_case.is_mine())
예제 #16
0
class Interface(Console):
    _default_config = {"retrieve": 2,
                       "adapt": True,
                       "auto_run": True,
                       "auto_display": True,
                       "verbose_results": False}

    def __init__(self, matcher):
        Console.__init__(self)
        self.config = self._default_config
        self.prompt = ">> "
        self.intro = "Welcome to the CBR system. Type 'help' for a list of commands."
        self.matcher = matcher
        if not self.matcher.cases:
            self.intro += "\nNOTE: Currently no cases loaded (you may want to run parser.py to generate some)!"

        self.query = Case()
        self.result = []
        if not sys.stdin.isatty():
            self.prompt = self.intro = ""
            self.interactive = False
            self.config['auto_run'] = False
        else:
            self.interactive = True


    def gen_help(self, method):
        """Generate a help message by removing extra spaces from doc strings"""
        if isinstance(method, str):
            helpstring = getattr(self.__class__, method).__doc__
        else:
            helpstring = method.__doc__
        return re.sub("\n *", "\n", helpstring)

    def do_help(self, arg):
        if arg in ('status', 'query', 'result', 'config', 'exit'):
            Console.do_help(self, arg)
        else:
            print("\n".join(['These are the accepted commands.',
                             'Type help <command> to get help on a specific command.',
                             '',
                             'status    Show summary of system status.',
                             'query     Manipulate and run query.',
                             'result    Show result of a query.',
                             'config    Set config variables.',
                             'exit      Exit application.']))

    def help_help(self):
        print(self.gen_help("do_help"), end=' ')

    def do_status(self, arg):
        """Print current status of system (i.e. how many cases loaded etc)."""
        print("Currently %d cases loaded." % len(self.matcher.cases))
        if self.query:
            print("Current query has %d attributes." % len(self.query))
        else:
            print("No current query.")
        if self.result:
            print("Result exists.")
        else:
            print("No result exists.")

    def help_status(self):
        print(self.gen_help("do_status"))

    def do_query(self, arg):
        """Manipulate the query.

        query [show]                   Show current query.
        query reset                    Reset query to be empty.
        query set <attribute> <value>  Set query attribute <attribute> to <value>.
        query unset <attribute>        Unset query attribute <attribute>.
        query names [attribute]        Show possible attribute names.
        query run                      Run the current query.

        By default, the query is automatically run when changed, and
        the result is automatically displayed when run. This behaviour
        can be changed by setting respectively the 'auto_run' and
        'auto_display' config parameters."""
        if arg in ('', 'show'):
            if self.query:
                print_table([self.query], ["Attribute", "Value"])
            else:
                print("No current query.")
        elif arg == "reset":
            self.query = Case()
        elif arg.startswith('set'):
            parts = arg.split(None, 2)
            if len(parts) < 3:
                print("Usage: query set <attribute> <value>.")
                return
            arg,key,val = parts
            try:
                self.query[key_name(key, possible_attributes)] = val
                if self.config['auto_run']:
                    self.do_query("run")
            except KeyError:
                print("Invalid attribute name '%s'." % key)
                print("Possible attribute names:")
                print("\n".join(["  "+i for i in sorted(possible_attributes.keys())]))
            except ValueError as e:
                print(str(e))
        elif arg.startswith('unset'):
            parts = arg.split()
            if len(parts) < 2:
                print("Usage: query unset <attribute>.")
                return
            arg,key = parts[:2]
            try:
                key = key_name(key, possible_attributes)
                del self.query[key]
                if self.config['auto_run']:
                    self.do_query("run")
            except KeyError:
                print("Attribute '%s' not found." % key)
                return
        elif arg.startswith('names'):
            parts = arg.split()
            if len(parts) < 2:
                print("Possible attributes:")
                print_table([dict([(k,v._weight) for (k,v) in list(possible_attributes.items())]),
                             dict([(k,v._adaptable) for (k,v) in list(possible_attributes.items())]),
                             dict([(k,v._adjustable) for (k,v) in list(possible_attributes.items())]),],
                            ["Attribute name", "Weight", "Adaptable", "Adjusted"])
                print("\n".join(("Weight is the weight of the attribute for case similarity.",
                                 "",
                                 "Adaptable specifies whether the attribute can be adapted to",
                                 "the query value.",
                                 "",
                                 "Adjustable specifies whether the attribute is adjusted based",
                                 "on the adaptable ones.",
                                 "",
                                 "Run 'query names <attribute>' for help on an attribute.")))

            else:
                try:
                    key = key_name(parts[1], possible_attributes)
                    attr = possible_attributes[key]
                    print("\n".join(("Attribute :  %s" % key,
                                     "Weight    :  %s" % attr._weight,
                                     "Adaptable :  %s" % attr._adaptable,
                                     "Adjusted  :  %s" % attr._adjustable,
                                     "")))
                    print(self.gen_help(attr))
                except KeyError:
                    print("Unrecognised attribute name: %s" % parts[1])
        elif arg.startswith('run'):
            if not self.query:
                print("No query to run.")
                return
            result = self.matcher.match(self.query, self.config['retrieve'])
            if result:
                if self.config['adapt']:
                    try:
                        result.insert(0, self.matcher.adapt(self.query, result))
                    except AdaptationError:
                        pass
                self.result = (Case(self.query), result)
                if self.config['auto_display']:
                    self.do_result("")
                elif self.interactive:
                    print("Query run successfully. Use the 'result' command to view the result.")
            else:
                print("no result.")
        else:
            print("Unrecognised argument. Type 'help query' for help.")

    def help_query(self):
        print(self.gen_help("do_query"))

    def complete_query(self, text, line, begidx, endidx):
        return self.completions(text, line, {'set': sorted(possible_attributes.keys()),
                                                   'names': sorted(possible_attributes.keys()),
                                                   'unset': list(self.query.keys()),
                                                   'show': [],
                                                   'reset': [],
                                                   'run': []})

    def do_result(self, args):
        """Print the current query result.

        Prints a table with the query result, each column
        corresponding to a result. The query that is printed along
        with the result.

        If the verbose_results config parameter is set (default: off),
        the similarities for each attribute is shown after the value
        in the form (normalised/weighed).

        If adaptation is turned on (which is the default; turn it off
        with 'config set adapt 0'), an adapted version of the best
        result is shown along with the results if adaptation is
        possible. Adaptation is possible if any of the parameters of
        the query are adaptable, and the query value differs from the
        value of the best result.

        No adaptation is done if the adapted result is worse (i.e. has
        a lower similarity) than the best query match. This can happen
        if the adjusted attribute is part of the query.

        Note that the query shown in the result can differ from the
        current one, if the query has been altered and not rerun (by
        default, the query is re-run whenever it is altered, but this
        can be changed with the 'auto_run' parameter."""
        if not self.result:
            print("No result.")
            return
        query,result = self.result
        header = ["Attribute", "Query"]
        results = [query]
        add = 1
        for i,(sim,res) in enumerate(result):
            if sim == 'adapted':
                header.append("Adapted result (sim. %.3f)" % query.similarity(res))
                add = 0
            else:
                header.append("Result %d (sim. %.3f)" % (i+add, sim))
            if self.config['verbose_results']:
                r = {}
                for k,v in list(res.items()):
                    if k in query:
                        s = query[k].similarity(v)
                        w = query[k].weight
                    else:
                        s = 1.0
                        w = 1.0
                    r[k] = "%s (%.2f/%.2f)" % (v, s/w, s)
                results.append(r)
            else:
                results.append(res)
        print_table(results,header)

    def help_result(self):
        print(self.gen_help("do_result"))

    def do_config(self, args):
        """View or set configuration variables.

        config [show]              Show current config.
        config set <key> <value>   Set <key> to <value>.

        Configuration keys:
        adapt:                     Whether or not to adapt the best case if not a perfect match.
        auto_display:              Automatically display results after running query.
        auto_run:                  Automatically run query when it changes.
        retrieve:                  How many cases to retrieve when running queries.
        verbose_results:           Show similarities (normalised/weighed) for each attribute."""
        if args in ('', 'show'):
            print("Current config:")
            print_table([self.config], ['Key', 'Value'])
        elif args.startswith('set'):
            parts = args.split(None, 2)
            if len(parts) < 3:
                print("Usage: config set <key> <value>.")
                return
            key,value = parts[1:3]
            if not key in self.config:
                print("Unrecognised config key: '%s'" % key)
            try:
                if type(self.config[key]) in (int, float):
                    self.config[key] = type(self.config[key])(value)
                elif type(self.config[key]) == bool:
                    if value.lower().strip() in ("1", "t", "y", "yes", "true"):
                        self.config[key] = True
                    elif value.lower().strip() in ("0", "f", "n", "no", "false"):
                        self.config[key] = False
                    else:
                        raise ValueError
            except ValueError:
                print("Invalid type for key %s: '%s'" % (key,value))
        else:
            print("Unrecognised argument.")
            self.help_config()

    def help_config(self):
        print(self.gen_help('do_config'))

    def complete_config(self, text, line, begidx, endidx):
        return self.completions(text, line, {'show': [],
                                             'set': list(self.config.keys())})

    def completions(self, text, line, completions):
        parts = line.split(None)
        current = []
        if len(parts) == 1 or (len(parts) == 2 and not parts[1] in list(completions.keys())):
            current = list(completions.keys())
        elif ((len(parts) == 2 and not text) or (len(parts) == 3) and text) and parts[1] in completions:
            current = completions[parts[1]]
        return [i+" " for i in current if i.lower().startswith(text.lower())]

    def completenames(self, text, line, begidx, endidx):
        completions = ['help', 'query', 'status', 'result', 'config', 'exit']
        if text==line:
            return [i+" " for i in completions if i.startswith(text)]
        return Console.completenames(self, text, line, begidx, endidx)

    def default(self, line):
        print("Invalid command. Type 'help' for a list of commands.")

    def postloop(self):
        cmd.Cmd.postloop(self)
        if self.interactive:
            print("Exiting...")
예제 #17
0
    def do_query(self, arg):
        """Manipulate the query.

        query [show]                   Show current query.
        query reset                    Reset query to be empty.
        query set <attribute> <value>  Set query attribute <attribute> to <value>.
        query unset <attribute>        Unset query attribute <attribute>.
        query names [attribute]        Show possible attribute names.
        query run                      Run the current query.

        By default, the query is automatically run when changed, and
        the result is automatically displayed when run. This behaviour
        can be changed by setting respectively the 'auto_run' and
        'auto_display' config parameters."""
        if arg in ('', 'show'):
            if self.query:
                print_table([self.query], ["Attribute", "Value"])
            else:
                print("No current query.")
        elif arg == "reset":
            self.query = Case()
        elif arg.startswith('set'):
            parts = arg.split(None, 2)
            if len(parts) < 3:
                print("Usage: query set <attribute> <value>.")
                return
            arg,key,val = parts
            try:
                self.query[key_name(key, possible_attributes)] = val
                if self.config['auto_run']:
                    self.do_query("run")
            except KeyError:
                print("Invalid attribute name '%s'." % key)
                print("Possible attribute names:")
                print("\n".join(["  "+i for i in sorted(possible_attributes.keys())]))
            except ValueError as e:
                print(str(e))
        elif arg.startswith('unset'):
            parts = arg.split()
            if len(parts) < 2:
                print("Usage: query unset <attribute>.")
                return
            arg,key = parts[:2]
            try:
                key = key_name(key, possible_attributes)
                del self.query[key]
                if self.config['auto_run']:
                    self.do_query("run")
            except KeyError:
                print("Attribute '%s' not found." % key)
                return
        elif arg.startswith('names'):
            parts = arg.split()
            if len(parts) < 2:
                print("Possible attributes:")
                print_table([dict([(k,v._weight) for (k,v) in list(possible_attributes.items())]),
                             dict([(k,v._adaptable) for (k,v) in list(possible_attributes.items())]),
                             dict([(k,v._adjustable) for (k,v) in list(possible_attributes.items())]),],
                            ["Attribute name", "Weight", "Adaptable", "Adjusted"])
                print("\n".join(("Weight is the weight of the attribute for case similarity.",
                                 "",
                                 "Adaptable specifies whether the attribute can be adapted to",
                                 "the query value.",
                                 "",
                                 "Adjustable specifies whether the attribute is adjusted based",
                                 "on the adaptable ones.",
                                 "",
                                 "Run 'query names <attribute>' for help on an attribute.")))

            else:
                try:
                    key = key_name(parts[1], possible_attributes)
                    attr = possible_attributes[key]
                    print("\n".join(("Attribute :  %s" % key,
                                     "Weight    :  %s" % attr._weight,
                                     "Adaptable :  %s" % attr._adaptable,
                                     "Adjusted  :  %s" % attr._adjustable,
                                     "")))
                    print(self.gen_help(attr))
                except KeyError:
                    print("Unrecognised attribute name: %s" % parts[1])
        elif arg.startswith('run'):
            if not self.query:
                print("No query to run.")
                return
            result = self.matcher.match(self.query, self.config['retrieve'])
            if result:
                if self.config['adapt']:
                    try:
                        result.insert(0, self.matcher.adapt(self.query, result))
                    except AdaptationError:
                        pass
                self.result = (Case(self.query), result)
                if self.config['auto_display']:
                    self.do_result("")
                elif self.interactive:
                    print("Query run successfully. Use the 'result' command to view the result.")
            else:
                print("no result.")
        else:
            print("Unrecognised argument. Type 'help query' for help.")
예제 #18
0
def __init__(self, protocol):
   Case.__init__(self, protocol)
예제 #19
0
 def test_safe_case_proximity(self):
     safe_case = Case(0)
     self.assertEquals("0", safe_case.mine_proximity())
     safe_case.add_mine_proximity()
     self.assertEquals("1", safe_case.mine_proximity())
예제 #20
0
파일: run.py 프로젝트: yuriyfilonov/muon
from case import Case
from kit import Kit
from classification import Classifier
from optimization import TrainingAlgorithm

kit = Kit()
case = Case(minified=False)

trainingData, validationData, testData = case.loadData()

classifier = Classifier()
trainingAlgorithm = TrainingAlgorithm()

trainingMetrics = trainingAlgorithm.train(classifier, trainingData, validationData)

# verificationMetrics = case.verify(classifier)

testMetrics = case.test(classifier, validationData, 1000)

submission = case.createSubmission(classifier, testData, 1000)

kit.dump(submission)
예제 #21
0
파일: makeplots.py 프로젝트: niyaa/paper
def calcSLowUpMax(caseList):
    caseList.sort(key=lambda l: l.Re)
    S = [0.01, 0.025, 0.04, 0.055, 0.07, 0.085, 0.1, 0.115, 0.13, 0.145, 0.16, 0.175, 0.19, 0.205, 0.22, 0.235, 0.25]
    Re= np.linspace(300, 2500, num=12, endpoint=True)
    out=[]
    
    book = xlwt.Workbook()
    sh = book.add_sheet("a" + str(caseList[0].alfa) + "_Sig_S")
    col=0
    newCol=False
    for key, group in groupby(caseList, lambda x: x.Re):
        row=0
        if newCol: col+=3
        newCol=False    
    
        alist = list(group)        
        s, sig = getSig_S(alist)
        
        i=0
        if s[0] > S[0]:
            for ss in S:
                if ss in s:
                    break
                s.insert(i, ss)
                sig.insert(i, calculateSigmaForS(caseList, ss, alist[0].Re))
                i=i+1
                
        if s[-1] < S[-1]:
            for ss in S:
                if ss not in s: continue
                if ss <= s[-1]:
                    continue
                else:
#                    print ss, alist[0].Re
                    s.insert(len(s), ss)
                    sig.insert(len(sig), calculateSigmaForS(caseList, ss, alist[0].Re))
#                    print s, sig
        
        if float(alist[0].alfa) == 3:    
            #extra manual ...
            if float(alist[0].Re) == 1900:
                ssig = calculateSigmaForS(caseList, 0.025, 1900)
                s.insert(1, 0.025)
                sig.insert(1, ssig)
#                print ssig
                
            #extra manual ...
            if float(alist[0].Re) == 1500:
                ssig = calculateSigmaForS(caseList, 0.025, 1500)
                s.insert(1, 0.025)
                sig.insert(1, ssig)
#                print ssig
        
        if max(sig) > 0:
            sh.write(row, col, "Re ")
            sh.write(row, col+1, alist[0].Re)
            row+=1
            for i in range(0,len(s)):
                sh.write(row, col, s[i])
                sh.write(row, col+1, sig[i])
                row+=1
            newCol=True
        
        marker = next(linecycler)
        snew = np.linspace(s[0], s[-1], num=100, endpoint=True)
        f1=interpolate.interp1d(s, sig, kind='cubic')
        f2=interpolate.interp1d(s, -np.array(sig), kind='cubic')
        line, = plt.plot(snew, f1(snew))
        line, = plt.plot(s, sig, marker=marker, color=line.get_color(), linestyle='None')                        
        line.set_label("Re "+str(alist[0].Re))
        
        #This Part looks for S_low, S_high, and S_max
        #look for the S crit
        if max(sig) > 0:
            case = Case()
            case.alfa=alist[0].alfa
            case.Re=alist[0].Re
            smax=0
            s_l=0
            s_u=0
            try:
                ss = 0.5*(s[0]+s[-1])
                smax=optimize.fmin(f2, ss, maxiter=100000, maxfun=100000, disp=False)[0]
                sigmax=f1(smax)
                plt.scatter(smax,sigmax)
            except Exception as error:
                smax=0
            
            if sig[-1] < 0: # there are two roots
                s_m = 0.1
                s_l = optimize.brentq(f1, s[0], s_m)
                s_u = optimize.brentq(f1, s_m, s[-1])
                plt.scatter(s_l,f1(s_l))
                plt.scatter(s_u,f1(s_u))
                print alist[0].Re, s_l, s_u, smax
            else: #there is one root
#                print alist[0].Re, max(sig)
                s_l = optimize.brentq(f1, s[0], s[-1])
                plt.scatter(s_l,f1(s_l))
                print alist[0].Re, s_l, smax
            case.smax=smax
            case.s_l=s_l
            case.s_u=s_u
            out.append(case)
       
    fontP = FontProperties()
    fontP.set_size('small')
    
    plt.legend(fancybox=True, shadow=True, loc='center left', bbox_to_anchor=(1, 0.5), prop = fontP)
    plt.grid()
    plt.show()
    book.save("out.dat")
    return out
예제 #22
0
 def test_mined_case(self):
     test_case = Case(1)
     self.assertTrue(test_case.is_mine())
예제 #23
0
 def test_mine_case_proximity(self):
     mine_case = Case(1)
     self.assertEquals("*", mine_case.mine_proximity())