def particle_iteration(self, it, helper, best_swarm, ns, lock): """The particle makes 3 movements and update the results""" op = numpy.random.choice(ns.operations) if op in [2, 3] and ns.attach: # movement to particle best particle_distance = 1 - self.best.likelihood / self.current_tree.likelihood if particle_distance > 0: clade_to_be_attached = self.best.phylogeny.get_clade_by_distance( particle_distance) clade_to_be_attached = clade_to_be_attached.copy().detach() clade_destination = numpy.random.choice( self.current_tree.phylogeny.get_clades()) clade_destination.attach_clade(self.current_tree, clade_to_be_attached) self.current_tree.phylogeny.losses_fix(self.current_tree, helper.mutation_number, helper.k, helper.max_deletions) # movement to swarm best swarm_distance = 1 - best_swarm.likelihood / self.current_tree.likelihood if swarm_distance > 0: clade_to_be_attached = best_swarm.phylogeny.get_clade_by_distance( swarm_distance) clade_to_be_attached = clade_to_be_attached.copy().detach() clade_destination = numpy.random.choice( self.current_tree.phylogeny.get_clades()) clade_destination.attach_clade(self.current_tree, clade_to_be_attached) self.current_tree.phylogeny.losses_fix(self.current_tree, helper.mutation_number, helper.k, helper.max_deletions) # inertia movement Operation.tree_operation(self.current_tree, op, helper.k, helper.gamma, helper.max_deletions) self.current_tree.phylogeny.losses_fix(self.current_tree, helper.mutation_number, helper.k, helper.max_deletions) # calculate lh lh = Tree.greedy_loglikelihood(self.current_tree, helper.matrix, helper.cells, helper.mutation_number) self.current_tree.likelihood = lh # update particle best if lh > self.best.likelihood: self.best = self.current_tree.copy() # update swarm best lock.acquire() if lh > ns.best_swarm.likelihood or lh == ns.best_swarm.likelihood and len( self.current_tree.losses_list) < len( ns.best_swarm.losses_list): ns.best_swarm = self.current_tree.copy() lock.release()
def getOperationDataBase(operationDataBasePath): operationDataBase = open(operationDataBasePath, "r") opDictList = json.load(operationDataBase) operationDataBase.close() opList = [] for opDict in opDictList: op = Operation() op.convertFromJson(opDict) opList.append(op) return opList
def __init__(self, n, g, genes, connections, costs): self.n = n self.g = g self.connections = connections self.fitness = Fitness(genes, costs) self.operation = Operation(self.fitness, connections) self.replace = Replace() self.individual = Individual(genes, self.fitness.get_fitness(genes)) self.population = self.initial_population() self.generations()
def run(self): option = -1 operation = Operation() while option != 0: print("""+-------------------Menu------------------+ Person Tree: 1. Load the data from the file. 2. Insert a new Person. 3. Inorder traverse 4. Breadth-First Traversal traverse 5. Search by Person ID 6. Delete by Person ID Exit: 0. Exit +-----------------------------------------.+ """) option = int(input("Enter Option:")) if option == 1: print("Choice 1: Load data from file and display") file = input("Please enter the find path:") operation.loadFile(file) if option == 2: print("Choice 2: Insert a new Person") operation.addNewPerson() if option == 3: print("Choice 3: Inorder traverse") operation.InorderTraverse() if option == 4: print("Choice 4: Breadth-First Traversal traverse") operation.Bfs() if option == 5: print("Choice 5: Search by Person ID") ID = input("Please insert the ID:") operation.SearchbyID(ID) if option == 6: print("Choice 6: Delete by Person ID") ID = input("Delete the person with the ID =") operation.DeleteByID(ID)
def parseOperationReportCA0(inputFile): content = inputFile.read() content = content.replace(" \n", " ") content = content.split("\n", 9)[9] content = content.replace("i? 1/2 ", "") debugPrint(content) opList = [] for line in content.split("\n"): if len(line.strip()) != 0: op = Operation() op.parse(line) opList.append(op) return opList
def main(): path = sys.argv[1] if not os.path.exists(path): print("Por favor passe o caminho do arquivo!") return file = open(path, 'r') expression = file.readline() stack = [] tree = Tree() t = tree.generateTree(expression) queue = [] tree.postOrder(t, queue) print(queue) op = Operation(t) print("Resultado e: " + str(op.solve()))
def particle_iteration_hill_2(it, p, helper): start_time = time.time() ops = list(range(0, Op.NUMBER)) result = -1 # while len(ops) > 0 and result != 0: op = ops.pop(random.randint(0, len(ops) - 1)) r = random.random() d_s, (_, highest_s) = p.current_tree.phylogeny.distance( helper, helper.best_particle.best.copy().phylogeny) d_p, (_, highest_p) = p.current_tree.phylogeny.distance( helper, p.best.copy().phylogeny) if r < .25: tree_copy = helper.best_particle.best.copy() elif r < .50: tree_copy = p.best.copy() elif r < .75: clade_to_attach = highest_s if d_s > d_p else highest_p tree_copy = Tree.random(helper.cells, helper.mutations, helper.mutation_names) tree_copy.phylogeny.attach_clade_and_fix(helper, tree_copy, clade_to_attach) else: tree_copy = p.current_tree.copy() result = Op.tree_operation(helper, tree_copy, op) return it, result, op, p, tree_copy, start_time
def __init__( self, function=None, copies=0, inbox=None, outbox=None, name='MultiTask', verbose=False ): # todo: priority, save cache, setup # initialize function carrier if function: if isinstance(function,Remember): if not isinstance(function.__cache__,Object): function.__cache__ = Object(function.__cache__) elif isinstance(function,Service): raise Exception, 'cannot create MultiTask() with a Service()' elif not isinstance(function,Operation): function = Operation(function) # initialize queues inbox = inbox or ShareableQueue() outbox = outbox or ShareableQueue() # check numer of copies if copies < 0: copies = max(mp.cpu_count()+(copies+1),0) # store self.function = function self.name = name self.inbox = inbox self.outbox = outbox self.copies = copies self.verbose = verbose # auto start if function: self.start()
def DoIt(self, host, vm, variable, value): """ This operation can set arbitrary key/value pairs for a VM running VMware Tools. This data is stored in the config.extraConfig VMODL property. Examples: $ ./vmware-cmd2 -H pioneer-131 'VirtualCenter 2.5 VM' getguestinfo marc getguestinfo(marc) = 101 $ ./vmware-cmd2 -H pioneer-131 'VirtualCenter 2.5 VM' setguestinfo marc 102 setguestinfo(marc, 102) = success $ ./vmware-cmd2 -H pioneer-131 'VirtualCenter 2.5 VM' getguestinfo marc getguestinfo(marc) = 102 $ ./vmware-cmd2 -H pioneer-131 'VirtualCenter 2.5 VM' getguestinfo abc None $ ./vmware-cmd2 -H pioneer-131 'VirtualCenter 2.5 VM' setguestinfo abc def setguestinfo(abc, def) = success $ ./vmware-cmd2 -H pioneer-131 'VirtualCenter 2.5 VM' getguestinfo abc getguestinfo(abc) = def """ vm = Operation.GetVm(host, vm) extraConfig = vm.GetExtraConfig() extraConfig['guestinfo.%s' % variable] = value return extraConfig.Save()
def DoGCodeCalls(self): Operation.DoGCodeCalls(self) if self.spindle_speed != 0: spindle(self.spindle_speed) feedrate_hv(self.horizontal_feed_rate / wx.GetApp().program.units, self.vertical_feed_rate / wx.GetApp().program.units) flush_nc()
def WriteXml(self): cad.BeginXmlChild('speedop') cad.SetXmlValue('hfeed', self.horizontal_feed_rate) cad.SetXmlValue('vfeed', self.vertical_feed_rate) cad.SetXmlValue('spin', self.spindle_speed) cad.EndXmlChild() Operation.WriteXml(self)
def greedy_loglikelihood(cls, helper, tree, data=None): "Gets maximum likelihood of a tree" nodes_list = tree.phylogeny.get_cached_content() node_genotypes = [ [0 for j in range(helper.mutations)] for i in range(len(nodes_list)) ] for i, n in enumerate(nodes_list): n.get_genotype_profile(node_genotypes[i]) maximum_likelihood = 0 for i in range(helper.cells): best_sigma = -1 best_lh = float("-inf") for n in range(len(nodes_list)): lh = 0 for j in range(helper.mutations): p = Op.prob(helper.matrix[i][j], node_genotypes[n][j], node_genotypes, helper, tree, data) lh += math.log(p) if lh > best_lh: best_sigma = n best_lh = lh tree.best_sigma[i] = best_sigma maximum_likelihood += best_lh return maximum_likelihood
def addNewSample(self, ex, ey, classId): newSample = numpy.array([[ex], [ey], [classId]]) self.__samples = numpy.append(self.__samples, newSample, axis=1) self.__mainwidget.runFeatureSpaceComputations(initialize=True) op = Operation(self.__featurespace, "Samples2D.addNewSample", newSample) self.__featurespace.getWidget().operationStack.add(op)
def main(): """ try: parser = Parser() args = parser.get_args() if args.csv is None: print "Please fill missing argument, check --help for additional information " except: print "expected one argument, check --help for additional information " """ op = Operation("input.csv") ################ must be arg.csv csv_reader = op.read_csv() op.extract_web_data(csv_reader)
def DoIt(self, host, vm, name, description, quiesce, memory): """ Example: $ ./vmware-cmd2 -H pivot02 mabramow-test1 hassnapshot hassnapshot() = 0 $ ./vmware-cmd2 -H pivot02 mabramow-test1 createsnapshot test_snapshot 'a test snapshot' 1 1 createsnapshot(test_snapshot, a test snapshot, 1, 1) = success $ ./vmware-cmd2 -H pivot02 mabramow-test1 hassnapshot hassnapshot() = 1 """ """ print('### CreateSnapshot.DoIt: ' + 'vm = %s; ' % vm + 'name = "%s"; ' % name + 'description = "%s"; ' % description + 'quiesce = %s; ' % bool(int(quiesce)) + 'memory = %s; ' % bool(int(memory))) """ vm = Operation.GetVm(host, vm) memory = self.GetParamValue(memory, 'memory') quiesce = self.GetParamValue(quiesce, 'quiesce') return vm.CreateSnapshot(name, description, memory, quiesce)
def deleteGaussian(self, gaussianId, confirmation = True): reply = QtWidgets.QMessageBox.Yes if confirmation: reply = QtWidgets.QMessageBox.question(self, 'Confirmation', "Do you really want to delete this Gaussian?", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No) if reply == QtWidgets.QMessageBox.Yes: for i, gaussian in enumerate(self.gaussians): if gaussian.getId() == gaussianId: break self.deletedGaussians.append(self.gaussians[i]) del self.gaussians[i] if confirmation: # if confirmation == False, the Gaussian was deleted by a redo operation op = Operation(self, "FeatureSpace.deleteGaussian", (gaussianId)) #self.__widget.operationStack.add(op) return (True, op) #self.repaint() return (False, None)
def importFile(self): filename = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', self.__dir, 'CSV (*.csv);;ASCII (*.txt);;all files(*.*)') if filename: i = 0 try: samples = numpy.empty(shape = (3, 0), dtype = numpy.float64) with open(filename, 'r') as f: for line in f.readlines(): i += 1 line = line.strip() parts = re.split('[, \t]+', line) x = float(parts[0]) y = float(parts[1]) l = int(parts[2]) sample = numpy.array([[x], [y], [l]]) if len(parts) == 3: samples = numpy.append(samples, sample, axis = 1) else: print('Corrupt line: {0}'.format(line), file=sys.stderr) op = Operation(self, "FeatureSpace.importFile", (samples)) self.__widget.operationStack.add(op) self.samples.addNewSamples(samples) except: if i > 0: msg = "Error importing feature space from {0} in line {1}: {2}".format(filename, i, line) else: msg = "Error importing feature space from {0}".format(filename) QtWidgets.QMessageBox.warning(self, 'Error', msg, QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Ok)
def deleteSamplesInSelectedArea(self): if self.__areaSelected: removeList = self.__updateList if len(removeList) > 0: area = (self.__area_x1, self.__area_y1, self.__area_x2, self.__area_y2) removeSamples = self.__samples[:, removeList] self.__samples = numpy.delete(self.__samples, removeList, axis=1) res = self.__mainwidget.runFeatureSpaceComputations( initialize=True) if not res: self.__featurespace.repaint() op = Operation(self.__featurespace, "Samples2D.deleteSamples", (removeSamples, removeList, area)) self.__featurespace.getWidget().operationStack.add(op) self.__areaSelected = False self.__dock.deleteButton.setEnabled(False) return len(removeList) return 0
def DoIt(self, host, vm, variable, value): """ @todo Currently, this is only handling config items that map to extraConfig so this is not complete. It needs to handle config items that map to specialized VMODL properties. $ ./vmware-cmd2 -H pioneer-131 'VirtualCenter 2.5 VM' getconfig annotation getconfig(annotation) = 'jhu VC 2.5 VM' [Bugs] ### ./vmware-cmd2 -H pioneer-131 'VirtualCenter 2.5 VM' setconfig annotation xyz None ### ./vmware-cmd2 -H pioneer-131 'VirtualCenter 2.5 VM' getconfig annotation getconfig(annotation) = 'jhu VC 2.5 VM' @todo Cannot do setconfig on annotation """ vm = Operation.GetVm(host, vm) extraConfig = vm.GetExtraConfig() if variable in extraConfig: extraConfig[variable] = value return extraConfig.Save()
def particle_iteration_clades(it, p, helper): start_time = time.time() ops = list(range(0, Op.NUMBER)) result = -1 # while len(ops) > 0 and result != 0: op = ops.pop(random.randint(0, len(ops) - 1)) r = random.random() best_swarm_copy = helper.best_particle.best.copy() best_particle_copy = p.best.copy() distance_particle = p.current_tree.phylogeny.distance( helper, best_particle_copy.phylogeny) distance_swarm = p.current_tree.phylogeny.distance( helper, best_swarm_copy.phylogeny) particle_clades = best_particle_copy.phylogeny.get_clades_max_nodes( max=distance_particle) swarm_clades = best_swarm_copy.phylogeny.get_clades_max_nodes( max=distance_swarm) max_clades = 2 if distance_particle < max_clades and distance_swarm < max_clades or len( particle_clades) == 0 and len(swarm_clades) == 0: tree_copy = p.current_tree.copy() result = Op.tree_operation(helper, tree_copy, op) else: clades_attach = [] if distance_particle == 0 or len(particle_clades) == 0: for i in range(max_clades): if len(swarm_clades) > 0: choice = random.choice(swarm_clades) clades_attach.append(choice) swarm_clades.remove(choice) elif distance_particle == 0 or len(swarm_clades) == 0: for i in range(max_clades): if len(swarm_clades) > 0: choice = random.choice(particle_clades) clades_attach.append(choice) particle_clades.remove(choice) else: for i in range(max_clades): ran = random.random() if ran < .5 and len(particle_clades) > 0: # particle clade choice = random.choice(particle_clades) elif len(swarm_clades) > 0: choice = random.choice(swarm_clades) clades_attach.append(choice) swarm_clades.remove(choice) tree_copy = p.current_tree.copy() for cl in clades_attach: cl_ = cl.detach().copy() cta = random.choice(tree_copy.phylogeny.get_clades()) cta.attach_clade_and_fix(helper, tree_copy, cl_) tree_copy.phylogeny.fix_for_losses(helper, tree_copy) return i, result, op, p, tree_copy, start_time
def read(self, tid, vid): if self.transactions[tid].is_aborted(): print(tid, 'is aborted') return sites = self.assignsite(int(vid[1:])) for sid in sites: if self.sites[sid].is_active(): self.add_tsites(tid, sid, vid) ret = self.sites[sid].read(self.transactions[tid], vid) if ret == None: self.transactions[tid].activate() return else: self.checkDeadlock(tid, ret, Operation('read', tid, vid)) return print('No site is available to read', vid, 'in', tid) self.add_waitlist(Operation('read', tid, vid))
def toggleExclusion(self, undoOperation=False): self.__excluded = not self.__excluded if not undoOperation: return Operation(self.__widget, "Gaussian2D.toggleExclusion", (self.__id)) return None
def GetRandomOperation(property, objects): objectsOfType = GetObjectsOfType(property.returnType, objects) if (len(objectsOfType) < 1): return None operation = choice(['=', '!=']) object = objectsOfType[SafeRandomRange(0, len(objectsOfType))] return Operation(property, operation, object)
def __init__(self, jobNr, problem_line): self.operations = [] for i in range(0, len(problem_line), 2): machine = problem_line[i] time = problem_line[i + 1] operationNr = int(i / 2) operation = Operation(machine, time, operationNr) self.jobNr = jobNr self.operations.append(operation)
class OperationTest(unittest.TestCase): """Test de Operation""" def setUp(self): print('setUp') self.fixture = Operation(2, 3) def tearDown(self): print('tearDown') def test_1_add(self): """Test de add""" self.obj = Operation(2, 3) self.assertEqual(self.obj.add(), 2 + 3) def test_2_add(self): """Test de add""" self.obj = Operation(2, 0) self.assertEqual(self.obj.add(), 2 + 0)
def DoIt(self, host, vm): """ Example: $ ./vmware-cmd2 -H sdk167 deletevm mabramow-test3 ??? """ vm = Operation.GetVm(host, vm) return vm.Destroy()
def DoIt(self, host, vm): """ Example: $ ./vmware-cmd2 -H pivot02 mabramow-test1 getstate getstate() = off """ vm = Operation.GetVm(host, vm) return vm.powerState
def setClassId(self, classId, undoOperation=False): if self.__classId != classId: oldClassId = self.__classId self.__classId = classId self.setColors() if not undoOperation: return Operation(self.__widget, "Gaussian2D.setClassId", (self.__id, self.__classId, oldClassId)) return None
def __init__(self, inputs, function=None, outbox=None): if function and not isinstance(function, Operation): function = Operation(function) self.inputs = inputs self.function = function self.outputs = None self.owner = os.getpid() self.folder = os.getcwd() self.outbox = outbox
def DoIt(self, host, vm): """ Example: $ ./vmware-cmd2 -H pioneer-131 'VirtualCenter 2.5 VM' getconfigfile getconfigfile() = /vmfs/volumes/44ee4eb7-28601011-5305-000e0c6dbc76/VirtualCenter 2.5 VM/VirtualCenter 2.5 VM.vmx """ vm = Operation.GetVm(host, vm) return vm.localPath
def FollowUid(user, client, logger): logger.debug("try to follow %d", user['id']) ops = Operation.FetchOps(user['id']) meFollowing = FriendShip.CheckFollow(client, BGApp.dev_uid, user['id']) meFollowed = FriendShip.CheckFollow(client, user['id'], BGApp.dev_uid) logger.debug("ops num %d meFollowing %d meFollowed %d" % (len(ops), meFollowing, meFollowed)) if len(ops) == 0 and not meFollowing and not meFollowed: client.post.friendships__create(uid=user['id']) op = Operation() op.uid = user['id'] op.type = Operation.FollowType op.state = Operation.Finished op.online = user['online_status'] op.followers = user['followers_count'] op.friends = user['friends_count'] op.statuses = user['statuses_count'] op.Save() return True return False
def __init__(self): Operation.__init__(self)
# 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. # 3. This notice may not be removed or altered from any source distribution. from Operation import Operation
import urllib class Downloader(Operation): LocalPath = '' UrlFile = ''
logger.debug("%d's followers increase %d" % (comWeb.uid, num)) if num > 1: num = 1 followers = comWeb.GetFollowers(client, num) for user in followers: if todayOpNum < todayMaxNum: ret = FollowUid(user, client, logger) if ret: logger.debug("follow success") todayOpNum += 1 continue else: logger.debug('follow failed') else: logger.debug("today's follow count reach max %d" % todayOpNum) op = Operation() op.uid = user['id'] op.type = Operation.AtType op.state = Operation.NotFinished op.online = user['online_status'] op.followers = user['followers_count'] op.friends = user['friends_count'] op.statuses = user['statuses_count'] op.Save() if not comWeb.followers == comDb.followers: logger.debug("%d's followers %d different from original %d" % (comWeb.uid, comWeb.followers, comDb.followers)) comDb.followers = comWeb.followers comDb.friends = comWeb.friends comDb.statuses = comWeb.statuses comDb.Save() RemoveSingle(singleFilePath)
# To change this license header, choose License Headers in Project Properties. # To change this template file, choose Tools | Templates # and open the template in the editor. from Operation import Operation __author__ = "talba" __date__ = "$10/04/2015 18:44:16$" operator_set = { '+': Operation.make_increment, '-': Operation.make_decrement, '*': Operation.make_multiplier, '/': Operation.make_divisor, '%': Operation.make_modulus, '**': Operation.make_power } if __name__ == "__main__": Operation.show('+', operator_set['+']) print("\n") Operation.show('-', operator_set['-']) print("\n") Operation.show('*', operator_set['*']) print("\n") Operation.show('/', operator_set['/']) print("\n") Operation.show('%', operator_set['%']) print("\n") Operation.show('**', operator_set['**'])