Ejemplo n.º 1
0
	def translatePosteriorQuantitiesTom(self):
		"Returns posterior summary shorthands useful for computation of posterior quantities e.g. posterior mean"
		"These quantities translate from Murphy's notation to Griffiths&Sanborn's notation"
		if self.observations != None:
			"Prior Params"
			a0 = dc(self.v0)
			sigma0 = dc(self.sigma0)
			u0 = dc(self.mu0)
			lambda0 = dc(self.k0)

			"Empirical Moments 1&2"
			s2 = np.var(self.observations) # Variance in the data?
			xbar = np.mean(self.observations) #sample mean of the data?

			"Posterior Params"
			lambdai = lambda0 + self.n
			ai = a0 + self.n
			ui = ((lambda0*u0)+(self.n*xbar))/(lambda0 + self.n)
			sigmai_topleft = (a0*sigma0)+((self.n-1)*s2)
			sigmai_topright = ((lambda0*self.n)/(lambda0+self.n))*pow(u0-xbar,2)
			sigmai_bottom = a0+self.n
			sigmai = (sigmai_topleft+sigmai_topright)/sigmai_bottom
			return ui,lambdai,ai,sigmai

		else: return None, None, None, None
Ejemplo n.º 2
0
def start_split_data(data_list):
    random_list = dc(data_list)
    random.shuffle(random_list)
    mark = 0
    acc_list = []
    for i in range(1):  # fold range
        test_list = []
        training_list = []
        index = 0
        while (mark < int(len(random_list))):
            for train_e in range(0, mark):
                training_list.append(random_list[train_e])
            else:
                index = mark
                mark = int(len(random_list) / 10) + index
                for test_element in range(index, mark):
                    test_list.append(random_list[test_element])
                for training_element in range(mark, int(len(random_list))):
                    training_list.append(random_list[training_element])

                    # fold completion
            root = Node(training_list)
            root.node_type = 'root'
            build_tree(root)
            predicted_list = []
            temp = dc(root)
            for element in test_list:
                predicted_list.append(class_finder(element, temp))
            acc_list.append(accuracy(test_list, predicted_list))
            break
    print(mean(acc_list))
Ejemplo n.º 3
0
    def __init__(self,system, epsAgent = RandomAgent(),
                 gamma = 0.9, lam = 0.9, eps = 0.05):
        self.system = dc(system)
        self.epsAgent = dc(epsAgent)
        self.numTrt = Agent.numTrt(system)
        self.numNodes = system.network.numNodes
        self.numValidTrt = Agent.numValidTrt(numNodes,numTrt)

        self.iters = 0

        self.q = [[0]*numValidTrt for i in range(1 << numNodes)]
        self.e = [[0]*numValidTrt for i in range(1 << numNodes)]
        self.c = [[0]*numValidTrt for i in range(1 << numNodes)]

        self.gamma = gamma
        self.lam = lam
        self.eps = eps

        self.system.cleanse()
        self.system.wipeTrt()
        self.system.start()

        self.epsAgent.applyTrt(self.system)

        self.st = self.system.infInd()
        self.at = combo2Ind(self.system.trtInd(),numNodes,numTrt)
Ejemplo n.º 4
0
	def update_info(self,infojson,globalpath):
		l1("Updating content for %s"%self.oname)
		# reset
		self.content['fields'] = dc(self.basefields) 
		self.content['trigger'] = dc(self.basetrigger)
		# update
		for f in sorted(self.content['files'].keys()):
			l2("%s: "%f)
			for field in self.content['files'][f].keys():
				if field=='colour': new_value = raw_input("%s? [%s(%s)]"%(field,str(self.content['files'][f][field]),str(infojson['colours'][self.content['files'][f]['tag']])))
				elif field=='xsec': new_value = raw_input("%s? [%s(%s)]"%(field,str(self.content['files'][f][field]),str(infojson['crosssections'][self.content['files'][f]['tag']])))
				elif field=='trigger': 
					rootf = TFile.Open(os.path.join(globalpath,f))
					h2 = rootf.FindObjectAny('TriggerNames;1')
					if not h2: sys.exit('TriggerNames;1 problematic for %s. Exiting'%f)
					trigarray = self.help_TrigArray(h2)
					rootf.Close()
					self.content['files'][f][field] = ','.join(trigarray)
					print "trigger: %s"%(self.content['files'][f][field])
				elif field=='npassed': 
					rootf = TFile.Open(os.path.join(globalpath,f))
					h1 = rootf.FindObjectAny('TriggerPass;1')
					if not h1: sys.exit('TriggerPass;1 problematic for %s. Exiting'%f)
					npassed = h1.GetBinContent(1)
					rootf.Close()
					self.content['files'][f][field] = "%d"%npassed
					print "npassed: %s"%(self.content['files'][f][field])
				else: new_value = raw_input("%s? [%s]"%(field,str(self.content['files'][f][field])))
				if not new_value == "": self.content['files'][f][field] = new_value
			for field in ['scale']:
				new_value = raw_input("%s? [%s]"%(field,"%f"%(float(self.content['files'][f]['npassed'])/float(self.content['files'][f]['xsec'])) if not float(self.content['files'][f]['xsec'])==-1 else "-1"))
				if not new_value == "": self.content['files'][f][field] = new_value
				else: self.content['files'][f][field] = "%f"%(float(self.content['files'][f]['npassed'])/float(self.content['files'][f]['xsec'])) if not float(self.content['files'][f]['xsec'])==-1 else "-1"
		self.print_info()
		self.write_info()
Ejemplo n.º 5
0
def getKFWght(opts,loadedSamples,sel,trg):	
	inroot('float nDat=0.0, nQCD=0.0, nBkg=0.0;')
	inroot('TH1F *hDat = new TH1F("hDat","hDat",1,0,1);')
	inroot('TH1F *hQCD = new TH1F("hQCD","hQCD",1,0,1);')
	inroot('TH1F *hBkg = new TH1F("hBkg","hBkg",1,0,1);')
	### LOOP over samples
	for s in loadedSamples:
		### Skip some
		if any([x in s['tag'] for x in ['JetMon','VBF','GluGlu']]): continue
		if opts.debug: l3("%sSample: %s%s"%(purple,s['tag'],plain))
		### Clean some
		if opts.debug and 'KFAC' in opts.weight[1]: l3("Option specified k-factor and puWt ignored in k-factor calculation.")
		opts.weightlocal = dc(opts.weight)
		opts.weightlocal[1] = list(set(opts.weight[1])-set(['KFAC','PU']))
		### Get cut and weight
		trg,trg_orig = trigData(opts,s,trg)
		cut = write_cuts(sel,trg,sample=s['tag'],jsonsamp=opts.jsonsamp,jsoncuts=opts.jsoncuts,weight=opts.weightlocal,trigequal=trigTruth(opts.usebool))[0]
		trg = dc(trg_orig)
		if opts.debug: l3("Cut: %s"%cut)
		### Data
		if 'Data' in s['tag'] or 'DataV' in s['tag']:
			inroot('%s.draw("%s","%s","%s")'%(s['pointer'],ROOT.hDat.GetName(),"0.5",cut))
		### QCD 
		elif 'QCD' in s['tag']:
			inroot('%s.draw("%s","%s","%s")'%(s['pointer'],ROOT.hQCD.GetName(),"0.5",cut))
		### Bkg
		else:
			inroot('%s.draw("%s","%s","%s")'%(s['pointer'],ROOT.hBkg.GetName(),"0.5",cut))
		print "Data: %8.2f  | Bkg: %8.2f  | QCD: %8.2f"%(ROOT.hDat.Integral(),ROOT.hBkg.Integral(),ROOT.hQCD.Integral())
	### finish
	KFWght = (ROOT.hDat.Integral()-ROOT.hBkg.Integral())/ROOT.hQCD.Integral()
	inroot('delete hDat; delete hQCD; delete hBkg;')
	if opts.debug: l2("KFWght calculated at: %f"%KFWght)
	return KFWght
Ejemplo n.º 6
0
    def __init__(self, inhibitory = 1.0,initialQ = 0.0, delta_c = 0.0, tau_c = 1.0, tau_r = 0.00000001, tau_e = 10.0*ms):
        assert(tau_c > 0)
        assert(tau_r > 0)
        assert(tau_e > 0)
        assert(delta_c >= 0)
        assert(inhibitory == 1 or inhibitory == -1)

        self.inhibitory = inhibitory
        self.q = dc(initialQ)
        self.delta_c = dc(delta_c)
        self.c = 0.0
        self.tau_c = dc(tau_c)
        self.tau_r = dc(tau_r)
        self.tau_e = dc(tau_e)
        self.state = 'A'
        self.trace_e = 0.0
        self.spiked = False
        self.etrack = 0
        self.epsilonsqtrack = 0
        self.epsilontrack = 0
        self.correctedcounter =0
        self.errorcorrelation = 0
        self.errortrack = 0
        self.avcounter = 1


        self.processed = False
        self.grad = 0
        self.samples = 0
Ejemplo n.º 7
0
def doRatio( num, den ) :
  num1 = dc(num)
  den1 = dc(den)
  ratio = dc(num1)
  ratio.Divide(num1,den1,1.,1.,'b')
  ratio.SetMinimum(0.7)
  ratio.SetMaximum(1.1)
  return ratio  
def bulk_process(folder, start_eid, her_name):
	searchstr = folder + '*.xml'
	
	cur_eid = dc(start_eid)
	
	for filename in glob.glob(searchstr):
		print filename
		next = process(filename, cur_eid, her_name)
		cur_eid = dc(next) + 1
Ejemplo n.º 9
0
	def __init__(self,oname):
		self.oname = oname
		self.content = {}
		self.content['files'] = {}
		self.content['other'] = []
		self.content['fields'] = {'fname':35,'npassed':12,'xsec':12,'scale':15,'tag':18,'trigger':35,'colour':8} # field lengths
		self.content['trigger'] = ['HLT_QuadPFJet75_55_35_20_BTagCSV_VBF_v* OR HLT_QuadPFJet75_55_38_20_BTagCSV_VBF_v* OR HLT_QuadPFJet78_61_44_31_BTagCSV_VBF_v* OR HLT_QuadPFJet82_65_48_35_BTagCSV_VBF_v*','HLT_QuadJet75_55_35_20_BTagIP_VBF_v* OR HLT_QuadJet75_55_38_20_BTagIP_VBF_v*','HLT_QuadPFJet75_55_35_20_BTagCSV_VBF_v*','HLT_QuadPFJet75_55_38_20_BTagCSV_VBF_v*','HLT_QuadPFJet78_61_44_31_BTagCSV_VBF_v*','HLT_QuadPFJet82_65_48_35_BTagCSV_VBF_v*','HLT_QuadJet75_55_35_20_BTagIP_VBF_v*','HLT_QuadJet75_55_38_20_BTagIP_VBF_v*','HLT_DiJet35_MJJ650_AllJets_DEta3p5_VBF_v*','HLT_DiJet35_MJJ700_AllJets_DEta3p5_VBF_v*','HLT_DiJet35_MJJ750_AllJets_DEta3p5_VBF_v*','HLT_QuadJet50_v*','HLT_PFJet80_v*','HLT_DiPFJetAve40_v*','HLT_DiPFJetAve80_v*']
		self.basefields = dc(self.content['fields'])
		self.basetrigger = dc(self.content['trigger'])
		self.read_info()
def start_split_data(data_list):
    random_list = dc(data_list)
    random.shuffle(random_list)
    mark = 0
    acc_list = []
    test_list = []
    training_list = []
    for i in range(10):  # fold range
        test_list = []
        training_list = []
        index = 0
        while (mark < int(len(random_list))):
            for train_ele in range(0, mark):
                training_list.append(random_list[train_ele])
            else:
                index = mark
                mark = int(len(random_list) / 10) + index
                for test_element in range(index, mark):
                    test_list.append(random_list[test_element])
                for training_element in range(mark, int(len(random_list))):
                    training_list.append(random_list[training_element])
                # print(training_list)
                # fold completion
                # creating validation set
                v_list = random.sample(list(training_list),
                                       int(len(training_list) * 0.25))
                for v_item in v_list:
                    if v_item in training_list:
                        training_list.remove(v_item)
                # print(len(training_list))
                # print(len(v_list))
                Node.v_list = v_list
                Node.children = []
                Node.leaf_children = []
                Node.temp_children = []
                Node.new_children = []
                Node.len_training_list = len(training_list)
                Node.old_pessi_err = \
                    (node_err_cal(training_list, max_class(training_list,
                                                           class_column),
                                  class_column) + 1) / Node.len_training_list
                root = Node(training_list)
                Node.root = root
                # print(root.data)
                root.node_type = 'root'
                build_tree(root)
                predicted_list = []
                temp_root = dc(root)
                for test_element in test_list:
                    predicted_list.append(class_finder(test_element,
                                                        temp_root))
                acc_list.append(
                    accuracy(test_list, predicted_list, class_column))
                break
    print(mean(acc_list))
Ejemplo n.º 11
0
def nuts(atoms, e, iterations, wtraj=None):
    traj = [atoms]
    configuration_list = []
    try:
        for m in range(iterations):
            # XXX ERRORR HERE
            # initialize momenta
            rand_momenta = np.random.normal(0, 1, (len(atoms), 3))
            atoms.set_momenta(rand_momenta)

            # get slice variable
            u = np.random.uniform(0, np.exp(-1 * traj[-1].get_total_energy()))
            # u = np.random.uniform(0, traj[-1].get_total_energy())
            # print u

            # initialize negative and positive directions
            neg_atoms = dc(traj[-1])
            pos_atoms = dc(traj[-1])

            c = [dc(traj[-1])]
            j, s = 0, 1
            while s == 1:
                print('depth', j, 'samples', 2 ** j)
                v = np.random.choice([-1, 1])
                if v == -1:
                    # build tree in negative direction
                    neg_atoms, _, cp, sp = buildtree(neg_atoms, u, v, j, e)
                else:
                    _, pos_atoms, cp, sp = buildtree(pos_atoms, u, v, j, e)

                if sp == 1:
                    c += cp
                datoms = pos_atoms.positions - neg_atoms.positions
                s = sp * \
                    (np.dot(datoms.flatten(),
                            neg_atoms.get_momenta().flatten()) >= 0) * \
                    (np.dot(datoms.flatten(),
                            pos_atoms.get_momenta().flatten()) >= 0)
                j += 1
            print(m, len(c))
            configuration_list.append(c)
            energies = np.asarray([atoms.get_total_energy() for atoms in c])
            sample_pos = np.random.choice(range(len(c)),
                                          p=np.exp(-energies) / np.exp(
                                              -energies).sum())
            # sample_pos = np.random.choice(range(len(C)))
            # sample_pos = np.argmin(energies)
            # XXX ERROR HERE
            if wtraj is not None:
                wtraj.write(atoms)
            traj.append(c[sample_pos])
    except KeyboardInterrupt:
        if wtraj is not None:
            wtraj.write(atoms)
    return traj, configuration_list
Ejemplo n.º 12
0
def trigData(opts,s,trg):
	#print "in: ",trg
	if s=="" and (not opts.datatrigger==[]):
		trg_orig = dc(trg)
		trg = opts.datatrigger[opts.trigger.index(trg)]
	elif (not s==None) and (not opts.datatrigger==[]) and any([x in s['tag'] for x in ['Data','DataV','JetMon']]):
		trg_orig = dc(trg)
		trg = opts.datatrigger[opts.trigger.index(trg)]
	else:
		trg_orig = dc(trg)
	#print "out: ",trg,trg_orig
	return trg, trg_orig
Ejemplo n.º 13
0
 def __init__(self, atoms, restart=None, logfile=None, trajectory=None,
              seed=None,
              verbose=False):
     Optimizer.__init__(self, atoms, restart, logfile, trajectory)
     atoms.get_forces()
     atoms.get_potential_energy()
     if seed is None:
         seed = np.random.randint(0, 2 ** 31)
     self.verbose = verbose
     self.random_state = RandomState(seed)
     self.starting_atoms = dc(atoms)
     self.traj = [dc(atoms)]
     self.pe = []
     self.metadata = {'seed': seed}
Ejemplo n.º 14
0
def do_fill(opts,fout,s,v,sel,trg,ref,KFWght=None,skipWght=None):
	# info
	l2("Filling for %s"%v['var'])
	# containers
	cuts = {}
	cutlabels = {}
	names = {}
	canvas = TCanvas("cfill","cfill",1200,1000)
	# trg
	trg, trg_orig = trigData(opts,s,trg)
	# names
	jsoninfo = json.loads(filecontent(opts.jsoninfo))
	names['global'] = getNames(opts,s,v,sel,trg_orig,ref)
	keepMapInfo = None
	if skipWght==True:
		keepMapInfo = [x for x in opts.weight[1] if (x[0:3]=='MAP' or x[0:3]=='FUN' or x[0:3]=='COR')]
		opts.weight[1] = [dc(x) for x in opts.weight[1] if not (x[0:3]=='MAP' or x[0:3] == 'FUN' or x[0:3]=='COR')]
	wpars = weightInfo(opts.weight,KFWght)

	# TEffi object
	TEffi = TEffiType(v)

	# looping over different tags
	for tag in ['Num','Den']:
		# cuts
		cuts[tag],cutlabels[tag] = write_cuts(sel,trg if tag=='Num' else ['None'],reftrig=ref,sample=s['tag'],jsonsamp=opts.jsonsamp,jsoncuts=opts.jsoncuts,weight=opts.weight,KFWght=KFWght,varskip=opts.skip+[v['root']],trigequal=trigTruth(opts.usebool))
		if opts.debug: l3("Cut %s: %s%s%s: %s"%(tag,blue,cutlabels[tag],plain,cuts[tag]))

		# loading/filling
		names[tag] = getNames(opts,s,v,sel,trg_orig if tag=='Num' else ['None'],ref,tag)
		if not s['tag'] in TEffi.h[tag] or TEffi.h[tag][s['tag']]==None:
			fout.Delete(names[tag]['hist'])
			TEffi.fill(s['pointer'],s['tag'],tag,names[tag],cuts[tag])
			if opts.debug: l3("%sFilled: %40s(N=%9d, Int=%9d)%s"%(yellow,TEffi.h[tag][s['tag']].GetName(),TEffi.h[tag][s['tag']].GetEntries(),TEffi.h[tag][s['tag']].Integral(),plain))
	
	# consider ratio
	tag = 'Rat'
	names[tag]  = getNames(opts,s,v,sel,trg_orig,ref,tag)
	TEffi.effi(names[tag],jsoninfo['colours'][s['tag']],markerStyle(s['tag'],jsoninfo['markers'][s['tag']],opts))

	# write histogram to file			
	path = "%s/%s/%s"%('turnonCurves',wpars,names['global']['path-turnon'])
	TEffi.write(fout,path)

	# clean
	#TEffi.delete()
	canvas.Close()
	trg = dc(trg_orig)
	if skipWght==True:
		opts.weight[1] += keepMapInfo
Ejemplo n.º 15
0
def start_split_data(data_list):
    random_list = dc(data_list)
    random.shuffle(random_list)
    mark = 0
    acc_list = []
    class_count = len(set(list(c[class_column] for c in data_list)))
    for i in range(10):  # fold range
        test_list = []
        training_list = []
        index = 0
        while (mark < int(len(random_list))):
            for train_ele in range(0, mark):
                training_list.append(random_list[train_ele])
            else:
                index = mark
                mark = int(len(random_list) / 10) + index
                for test_element in range(index, mark):
                    test_list.append(random_list[test_element])
                for training_element in range(mark, int(len(random_list))):
                    training_list.append(random_list[training_element])
                    # print(training_list)
                    # fold completion
                Node.children = []
                Node.leaf_children = []
                Node.temp_children = []
                Node.new_children = []
                Node.len_training_list = len(training_list)
                Node.class_count = class_count
                Node.old_mdl = \
                    (Node.node_count - Node.leaf_node_count) * \
                    log2(len(column_names)) \
                    + \
                    (Node.leaf_node_count * log2(Node.class_count))\
                    +\
                    (len(data_list) * log2(len(data_list)))
                
                root = Node(training_list)
                # print(root.data)
                root.node_type = 'root'
                build_tree(root)
                predicted_list = []
                temp_root = dc(root)
                for test_element in test_list:
                    predicted_list.append(
                        class_finder(test_element, temp_root))
                acc_list.append(
                    accuracy(test_list, predicted_list, class_column))
                break
    print(mean(acc_list))
Ejemplo n.º 16
0
def check_dict_alg(dic, validator, entry_list, messages, whole_validator, current_elem):
    """This function does the real validation work by working through the validator.

    :param dic: The dictionary you want to validate.
    :type dic: dict
    :param validator: The validator you want to validate against.
    :type validator: dict
    :param entry_list: This list contains all keys you have to traverse to get the correct value in the dictionary.
    :type entry_list: list
    :param messages: The message list you want to append the error messages to.
    :type messages: dict
    :param whole_validator: This is a copy of the whole validator needed when referencing to a top level key.
    :type whole_validator: dict
    :param current_elem: The current element the alg is checking.
    :type current_elem: str
    :return: Nothing.

    """
    for node in validator:
        print("Checking node ", node)
        new_list = dc(entry_list)
        node_value = validator[node]
        if node != 'isReference':
            if not ('isReference' in node_value and len(entry_list) == 0):
                if is_operator(node):
                    handle_operator(node, dic, validator, new_list, messages, whole_validator, current_elem)
                elif is_leaf(node_value):
                    new_list.append(node)
                    check_leaf(node_value, dic, new_list, messages, current_elem)
                else:
                    new_list.append(node)
                    check_dict_alg(dic, node_value, new_list, messages, whole_validator, current_elem)
Ejemplo n.º 17
0
 def fromPol(cls,pol,copyPol=True):
     a = cls()
     if copyPol:
         a.pol = dc(pol)
     else:
         a.pol = pol
     return a
Ejemplo n.º 18
0
def shell_dynstep_sort(sequence):
    '''
    希尔排序
    动态改变步长
    '''
    seq = dc(sequence)
    pass
Ejemplo n.º 19
0
    def svd(self):
        """SVD filter"""

        self.fspec=np.zeros(self.spec.shape)
        self.u=[]
        self.s=[]
        self.v=[]

        for k in range(self.nscan):
            sind=self.getscanind(k)
            x=self.spec[sind]
            x[np.isnan(x)]=0
            u,s,v=np.linalg.svd(x,full_matrices=True)
            ss=dc(s)
            ss[0]=0
            SS=np.zeros(x.shape)
            
            sz=x.shape[0]
            SS[:sz,:sz]=np.diag(ss);
            z=np.dot(u,np.dot(SS,v))
            
            #for k in range(sz):
            #    y=z[k];ind=np.arange(500,1000);p=np.polyfit(self.f[ind],y[ind],deg=3);
            #    z[k]=y-np.poly1d(p)(self.f);
            self.fspec[sind]=z
            self.u.append(u)
            self.s.append(s)
            self.v.append(v)

        return u,s,v,self.fspec
Ejemplo n.º 20
0
def runsim(din=None):

    if din is None:
        # Dummy trajectory
        din=reduc_spec.data((2016,6,25,5,13,45),(2016,6,25,5,45,0))
    d=dc(din)

    # Sky model, only atmosphere and CMB (included as T0 param to am) for now
    #sm=skymodel(comp=['atm','cmb'])
    sm=skymodel(comp=['atm'])

    # Signal only (in K)
    d=gensig().run(d,sm)

    # Add noise
    d=addTrx(d,Trx=150)
    
    # Mock ambient temp cal stares
    d=makecal(d)

    # Convert to power units    
    d=T2I(d)

    # Multiply by gain
    d=multgain(d)
    
    # Add non-linearity
    d=addnonlin(d,0.01)

    return d
Ejemplo n.º 21
0
def convert_adjacency(cells, spacing, J, adj=None):
    """Convert the J matrix of a QCACircuit to the specified adjacency type."""

    if adj is None:
        return dc(J)

    params = prepare_convert_adj(cells, spacing, J)

    if adj == "full":
        J_ = convert_to_full_adjacency(J, *params)
    elif adj == "lim":
        J_ = convert_to_lim_adjacency(J, *params)
    else:
        J_ = dc(J)

    return J_
Ejemplo n.º 22
0
 def infer_diag_post(self,X_ii,D_i):
     
     X_i = dc(X_ii)
     ns = len(D_i)
     
     X_i.resize([ns,self.D])
     [m,V] = self.infer_diag(X_i,D_i)
     if sp.amin(V)<=-0.:
         class MJMError(Exception):
             pass
         print "negative/eq variance"
         print [m,V,X_i,D_i]
         print "_______________"
         #self.printc()
         raise(MJMError)
     if sp.amin(sp.var(m,axis=0))<-0.:
         class MJMError(Exception):
             pass
         print "negativevar of mean"
         print X_i.shape
         print [m,V,sp.var(m,axis=0),X_i,D_i]
         print "_______________"
         #self.printc()
         raise(MJMError)
     
     return [sp.mean(m,axis=0).reshape([1,ns]),(sp.mean(V,axis=0)+sp.var(m,axis=0)).reshape([1,ns])]
Ejemplo n.º 23
0
def convert_adjacency(cells, spacing, J, adj=None):
    '''Convert the J matrix of a QCACircuit to the specified adjacency type.'''

    if adj is None:
        return dc(J)    # deepcopy

    params = prepare_convert_adj(cells, spacing, J)

    if adj=='full':
        J_ = convert_to_full_adjacency(J, *params)
    elif adj=='lim':
        J_ = convert_to_lim_adjacency(J, *params)
    else:
        J_ = dc(J)

    return J_
Ejemplo n.º 24
0
def check_dict_alg(dic, validator, entry_list, messages, whole_validator, current_elem):
    """This function does the real validation work by working through the validation.

    Args:
      dic(dict): The dictionary you want to validate.
      validator(dict): The validation you want to validate against.
      entry_list(list: list): This list contains all keys you have to traverse to get the correct value in the dictionary.
      messages(dict): The message list you want to append the error messages to.
      whole_validator(dict): This is a copy of the whole validation needed when referencing to a top level key.
      current_elem(str): The current element the alg is checking.
      entry_list: 

    Returns:

    """
    for node in validator:
        new_list = dc(entry_list)
        node_value = validator[node]
        if node != 'isReference':
            if not ('isReference' in node_value and len(entry_list) == 0):
                if is_operator(node):
                    handle_operator(
                        node, dic, validator, new_list, messages, whole_validator, current_elem
                    )
                elif is_leaf(node_value):
                    new_list.append(node)
                    check_leaf(node_value, dic, new_list, messages, current_elem)
                else:
                    new_list.append(node)
                    check_dict_alg(
                        dic, node_value, new_list, messages, whole_validator, current_elem
                    )
Ejemplo n.º 25
0
def leapfrog(atoms, step, center=True):
    """
    Propagate the dynamics of the system via the leapfrog algorithm one step

    Parameters
    -----------
    atoms: ase.Atoms
        The atomic configuration for the system
    step: float
        The step size for the simulation, the new momentum/velocity is step *
        the force
    center: bool
        If true, center the atoms in the cell after moving them

    Returns
    -------
    ase.Atoms
        The new atomic positions and velocities
    """
    latoms = dc(atoms)

    latoms.set_momenta(latoms.get_momenta() + 0.5 * step * latoms.get_forces())

    latoms.positions += step * latoms.get_velocities()

    latoms.set_momenta(latoms.get_momenta() + 0.5 * step * latoms.get_forces())
    if center:
        latoms.center()
    return latoms
Ejemplo n.º 26
0
def do_fill(opts,fout,s,v,sel,trg,ref,KFWght=None):
	trg,trg_orig = trigData(opts,s,trg)
	# cut
	cut,cutlabel = write_cuts(sel,trg,reftrig=ref,sample=s['tag'],jsonsamp=opts.jsonsamp,jsoncuts=opts.jsoncuts,weight=opts.weight,KFWght=KFWght,trigequal=trigTruth(opts.usebool))
	if opts.debug: l3("Cut: %s%s%s: %s"%(blue,cutlabel,plain,cut))

	# names
	sample = s['pointer']
	names  = getNames(opts,s,v,sel,trg_orig,ref)
	wpars  = weightInfo(opts.weight,KFWght)

	# containers
	canvas = TCanvas("cfill","cfill",1200,800)
	fout.Delete(names['hist'])
	h      = TH1F(names['hist'],names['hist-title'],int(v['nbins_x']),float(v['xmin']),float(v['xmax']))
	h.Sumw2()
	
	# do actual filling
	inroot('%s.draw("%s","%s","%s")'%(sample,h.GetName(),v['root'],cut))
	if opts.debug: l3("%sFilled: %40s(N=%9d, Int=%9d)%s"%(yellow,h.GetName(),h.GetEntries(),h.Integral(),plain))
	
	# write histogram to file
	gDirectory.cd('%s:/'%fout.GetName())
	path = "%s/%s/%s"%('plots',wpars,names['path-hist'])
	makeDirsRoot(fout,path)
	gDirectory.cd(path)
	h.Write(h.GetName(),TH1.kOverwrite)
	gDirectory.cd('%s:/'%fout.GetName())

	# clean
	h.Delete()
	canvas.Close()
	trg = dc(trg_orig)
Ejemplo n.º 27
0
 def fromQ(cls,q,copyQ=True):
     a = cls()
     if copyQ:
         a.q = dc(q)
     else:
         a.q = q
     return a
Ejemplo n.º 28
0
 def __init__(self,h=None):  # initialization using a hamiltonian
   self.file_right_green = "green_right.dat"  # in/out file for right green
   self.file_left_green = "green_left.dat"   # in/out file for left green
   self.file_heff = "heff.dat"   # out for the effective hamiltonian
   self.scale_rc = 1.0 # scale coupling to the right lead
   self.scale_lc = 1.0 # scale coupling to the left lead
   self.is_sparse = False
   self.dimensionality = 1 # default is one dimensional
   self.delta = 0.0001
   self.interpolated_selfenergy = False
   self.block_diagonal = False
   if h is not None:
     self.heff = None  # effective hamiltonian
     self.right_intra = h.intra  # intraterm in the right lead
     self.right_inter = h.inter  # interterm in the right lead (to the right)
     self.right_green = None  # right green function
     self.left_intra = h.intra  # intraterm in the left lead
     self.left_inter = h.inter.H  # interterm in the left lead (to the left)
     self.left_green = None  # left green function
     self.central_intra = h.intra  # intraterm in the center
     self.right_coupling = h.inter # coupling from the center to the right lead
     self.left_coupling = h.inter.H # coupling from the center to the left lead
     # geometry of the central part
     gc = dc(h.geometry)
     self.central_geometry = gc # geometry of the central part
     # additional degrees of freedom
     self.has_spin = h.has_spin   # spin degree of freedom
     self.has_eh = h.has_eh   # electron hole pairs
Ejemplo n.º 29
0
def bellRes(iters,system,agent,q,gamma = 0.9):
    system = dc(system)
    numNodes = system.network.numNodes

    iters = iter(iters)

    sa = iters.next()

    system.infCmb(cmb = sa[0])
    system.trtCmb(cmb = sa[1])

    q0 = q(system)

    br = 0.0

    nIters = 0

    for sap in iters:
        system.infCmb(cmb = sap[0])
        system.wipeTrt()

        r = systems.reward(sa[0],sa[1],sap[0],numNodes)

        agent.applyTrt(system)

        q1 = q(system)

        br += q0 - r - gamma * q1
        nIters += 1

    br /= float(nIters)

    return br
Ejemplo n.º 30
0
def ring_blur_mask(img, geometry, alpha, bins=None, mask=None):
    if mask is None:
        mask = np.zeros(img.shape).astype(bool)
    r = geometry.rArray(img.shape)
    int_r = np.around(r / geometry.pixel1).astype(int)
    if bins is None:
        bins = int_r.max() + 1
    mr = dc(r)
    mr[mask] = -1

    # integration
    mean = sts.binned_statistic(mr.ravel(), img.ravel(), bins=bins,
                                range=[0, mr.max()], statistic='mean')[0]
    std = sts.binned_statistic(mr.ravel(), img.ravel(), bins=bins,
                               range=[0, mr.max()], statistic=np.std)[0]

    threshold = alpha * std
    lower = mean - threshold
    upper = mean + threshold

    # single out the too low and too high pixels
    too_low = img < lower[int_r]
    too_hi = img > upper[int_r]

    mask = mask | too_low | too_hi
    return mask.astype(int)
Ejemplo n.º 31
0
Archivo: gcmc.py Proyecto: s-dale/pyIID
def del_atom(atoms, chem_potentials, beta, random_state):
    """

    Parameters
    ----------
    atoms: ase.Atoms object
        The atomic configuration
    chem_potentials: dict
        A dictionary of {"Chemical Symbol": mu} where mu is a float denoting
        the chemical potential
    beta: float
        The thermodynamic beta
    random_state: np.random.RandomState object
        The random state to be used

    Returns
    -------
    atoms or None:
        If the new configuration is accepted then the new atomic configuration
        is returned, else None


    """
    if len(atoms) <= 1:
        return None
    print(len(atoms))
    # make the proposed system
    atoms_prime = dc(atoms)
    e0 = atoms.get_potential_energy()
    del_atom_index = random_state.choice(range(len(atoms)))
    del_symbol = atoms_prime[del_atom_index].symbol

    # append new atom to system
    del atoms_prime[del_atom_index]

    # get new energy
    delta_energy = atoms_prime.get_potential_energy() - e0
    # get chemical potential
    # print delta_energy
    mu = chem_potentials[del_symbol]
    # calculate acceptance
    if np.random.random() < np.exp(
            min([0, -1. * beta * delta_energy - beta * mu
                 ])) and not np.isnan(delta_energy):
        return atoms_prime
    else:
        return None
Ejemplo n.º 32
0
    def train(self, iterations=10, maxmiss=10):
        """
        Train using Recommended Greedy Algorithm
        """

        scores = {
            'Iteration': [],
            #'Network':[],
            'Score': []
        }
        score_check = maxmiss
        niter = iterations
        best = score_pom(export_pom(self.net, by='label'), self.data)

        #print("START LOOP")
        while score_check > 0 and niter > 0:
            n = dc(self.net)
            upd = set()

            ops = [n.add_edge, n.del_edge, n.rev_edge]
            for f in ops:
                edge = rn.sample(self.E, 1)[0]
                f(edge[0], edge[1])
                upd.add(edge[0])
                upd.add(edge[1])

            if n.acyclic():
                n.calc_cpt(self.data, alpha=self.alpha, change=upd)
                score = score_pom(export_pom(n, by='label'), self.data)
                scores['Iteration'].append(iterations - niter)
                #scores['Network'].append(n)
                scores['Score'].append(score)
                #print(best, score, niter, score_check)
                if score > best:
                    self.net = n
                    best = score
                    niter = niter - 1
                    score_check = maxmiss
                    continue
                else:
                    score_check = score_check - 1
                    niter = niter - 1
                    continue
            else:
                niter = niter - 1
                continue
        self.scores = scores
Ejemplo n.º 33
0
def next_move(obj, piece, pre, board, move_number, depth):
    '''CORE CONTROLLER'''
    if move_number == 1:
        return (2, 1)
    if move_number == 2:
        options = [(2, 1), (2, 2), (2, 3), (1, 2), (3, 2), (1, 1), (3, 3)]
        for opt in options:
            if board[opt[0]][opt[1]] == 0 and obj.get_liberty_single(
                    opt[0], opt[1])[1] == 4:
                return opt

    obj1 = dc(obj)
    available = obj1.get_valid_locations(piece)
    if len(available) == 0 or move_number > 24:
        return "PASS"
    if depth == -100:
        # greedy
        bestEval = -float('inf')
        for child in available:
            val = greedy(obj1, piece, child[0], child[1])
            if val > bestEval:
                bestEval = val
                best_child = child
    else:
        best_child = available[0]
        best_immediate = available[0]
        maxEval = -float('inf')
        maxImm = -float('inf')
        for child in available:
            md = depth
            immediate_kills = greedy(obj1, piece, child[0], child[1])
            if immediate_kills > maxImm:
                maxImm = immediate_kills
                best_immediate = child
        if maxImm > 1:
            return best_immediate

        for child in available:
            md = depth
            val = alphabeta(obj1, piece, child[0], child[1], md, -float('inf'),
                            float('inf'), True, move_number)
            if val > maxEval:
                best_child = child
                maxEval = val

    return best_child
Ejemplo n.º 34
0
    def periodic_standardize(self, factor: str, prefix: str = 'std_'):
        """
        Standardize a factor periodically.

        :param factor: (str) The name of factor will be standardized.
        :param prefix: (str) The prefix preceding a name of standardized factor.

        :return standardized_companies: (DataFrame) Standardized companies for each period by factor.
        """
        unstandardized_companies = dc(self.loc[~np.isnan(self[factor]), :])
        unstandardized_companies[prefix +
                                 factor] = unstandardized_companies.groupby(
                                     by=[DATE])[factor].transform(
                                         lambda x: (x - x.mean()) / x.std())
        standardized_companies = unstandardized_companies

        return standardized_companies
Ejemplo n.º 35
0
def hidden_board(Ctn):
    hidden_indexes = set(range(len(Ctn.hexagons)))
    prmpt = 'Choose yellow tile number to reveal (or type quit to exit): '
    clear_Catan(Ctn)
    distribute_resources(Ctn)
    distribute_numbers(Ctn)
    nIMG = dc(Ctn.IMG)
    for i in range(len(Ctn.hexagons)):
        hexagon = Ctn.hexagons[i]
        nIMG = replace_with_res(nIMG, Ctn.unit_hex, hexagon, Ctn.Res, 'water')
        nIMG = place_unplotted_number(nIMG, i, hexagon)
    plot_board(nIMG)
    print("You have the following options: ")
    print("1) Type quit to exit out of the program.")
    print("2) Type an integer of a yellow number hex to reveal it.")
    print("3) To reveal multiple hexes at a time, separate the integers "+\
    "with a comma with no space inbetween (e.g. 3,4,6)")
    print("4) Type all to reveal the remaining hidden hexes.")
    while len(hidden_indexes) != 0:
        reveal_index = input(prmpt)
        if reveal_index == 'quit':
            break
        elif reveal_index == 'all':
            for i in hidden_indexes:
                hexagon = Ctn.hexagons[i]
                nIMG = replace_with_res(nIMG, Ctn.unit_hex, hexagon, Ctn.Res)
                nIMG = place_number(nIMG, hexagon.number, Ctn.Nums, hexagon)
            plot_board(nIMG)
            break
        indexes = reveal_index.split(',')
        for hex_index in indexes:
            try:
                i = int(hex_index)
            except ValueError:
                print("Unrecognized value entered. Make sure it is an "+\
                "integer which has not been revealed yet. Try again... ")
                continue
            if i not in hidden_indexes:
                print("Either this number has already been revealed or it "+\
                "is not on the board. Try again... ")
                continue
            hexagon = Ctn.hexagons[i]
            nIMG = replace_with_res(nIMG, Ctn.unit_hex, hexagon, Ctn.Res)
            nIMG = place_number(nIMG, hexagon.number, Ctn.Nums, hexagon)
            hidden_indexes.remove(i)
        plot_board(nIMG)
Ejemplo n.º 36
0
def quicksort(numere):
    lista = dc(numere)
    less = []
    equal = []
    greater = []
    if len(lista) > 1:
        pivot = lista[0]
        for x in lista:
            if x < pivot:
                less.append(x)
            elif x == pivot:
                equal.append(x)
            elif x > pivot:
                greater.append(x)
        return quicksort(less) + equal + quicksort(greater)
    else:
        return lista
def sub_mean(matrix_, type='user'):
    matrix = dc(matrix_)
    c = Counter(matrix.nonzero()[0])
    means_matrix = matrix.sum(axis=1)
    means_matrix = np.reshape(means_matrix, [means_matrix.shape[0], 1])
    for i in range(means_matrix.shape[0]):
        if i in list(c.keys()):
            means_matrix[i, 0] = means_matrix[i, 0] / float(c[i])
        else:
            means_matrix[i, 0] = 0

    mask = matrix != 0
    nz_val = np.array(np.nonzero(matrix))
    nz_val = list(zip(nz_val[0], nz_val[1]))
    for val in nz_val:
        matrix[val[0], val[1]] -= means_matrix[val[0]]
    return matrix
Ejemplo n.º 38
0
    def obl_parametry(self, arg, wart):
        """
        dopasowuje parametry funkcji scatcharda do danych b i b/F -
        :return: zapisuje parametry jako self.parametry
        """
        #TODO NIE WYCH
        something_is = False
        nr_comb = 0
        max_r = 0
        while True:
            try:
                parametry_wejsciowe = np.array(comb[nr_comb])
            except:
                if something_is:
                    pass
                    # print("znaleziono nieoptymalne parametry")
                else:
                    print("NIE znaleziono optymalnych parametrów")
                break
            nr_comb += 1
            # print(comb[nr_comb])
            try:
                # if len(arg) <= 4 or len(wart) != len(arg):
                # print(len(arg),len(wart))
                # if len(arg) <= 2:
                #     print(self.nazwa, self.zwrot_ok(), len(self.szczury))
                parametry = curve_fit(scatchard_curv,
                                      arg,
                                      wart,
                                      p0=parametry_wejsciowe,
                                      bounds=[0, 300])[0]
                r = get_r(*self.zwrot_ok()[0:2], parametry)
                if r > max_r:
                    max_r = r
                    self.parametry = dc(parametry)
                if r >= 0.98:
                    with open("optimal_start_params.txt", 'a') as plik:
                        plik.write(str(parametry_wejsciowe) + '\n')
                    print('znaleziono optymalne parametry')
                    break
                something_is = True
                with open("good_start_params.txt", 'a') as plik:
                    plik.write(str(parametry_wejsciowe) + '\n')

            except:
                pass
Ejemplo n.º 39
0
def build_flash_data(data, required_measures):
    flash_data = {}
    for sensor_id in required_measures:
        sensor_type = required_measures[sensor_id]["type"]
        sensor_period = required_measures[sensor_id]["period"]

        flash_data[sensor_id] = dc(data[sensor_type])
        flash_data[sensor_id]["records"] = []
        flash_data[sensor_id]["type"] = sensor_type
        flash_data[sensor_id]["period"] = sensor_period

        # build an array containing boolean value corresponding to the item in the array of the possible measurment
        for measure in data[sensor_type]["value"]:
            flash_data[sensor_id]["records"].append(
                measure in required_measures[sensor_id]["measure"])

    return flash_data
Ejemplo n.º 40
0
    def Fill(self):

        if self.legpos == 0: self.leg = ROOT.TLegend(0.5, 0.3, 0.88, 0.6)
        if self.legpos == 1: self.leg = ROOT.TLegend(0.35, 0.73, 0.88, 0.88)
        if self.legpos == 2: self.leg = ROOT.TLegend(0.4, 0.25, 0.88, 0.7)
        if self.legpos == 3: self.leg = ROOT.TLegend(0.5, 0.7, 0.88, 0.88)
        if self.legpos == 4: self.leg = ROOT.TLegend(0.4, 0.16, 0.88, 0.35)
        if self.legpos == 5: self.leg = ROOT.TLegend(0.4, 0.16, 0.88, 0.5)
        if self.legpos == 6: self.leg = ROOT.TLegend(0.25, 0.16, 0.88, 0.5)
        if self.legpos == 7: self.leg = ROOT.TLegend(0.6, 0.2, 0.88, 0.3)
        if self.legpos == 8: self.leg = ROOT.TLegend(0.3, 0.16, 0.88, 0.35)
        if self.legpos == 9: self.leg = ROOT.TLegend(0.3, 0.16, 0.88, 0.5)
        if self.legpos == 10: self.leg = ROOT.TLegend(0.22, 0.16, 0.88, 0.35)
        self.leg.SetTextSize(0.027)
        self.leg.SetFillColor(ROOT.kWhite)
        self.leg.SetLineColor(ROOT.kWhite)

        myjson = {}
        for i, graph in enumerate(self.graphs):

            if graph.function:
                print '\n=====> Fitting %s' % graph.graph
                fitter = Fitter(graph.graph,
                                graph.function,
                                colour=graph.colour)
                graph.graph, graph.grapherror, results = fitter._fit()
                graph.fittedfunction = dc(graph.function)
                graph.fittedfunction.SetName(graph.fittedfunction.GetName() +
                                             '%d' % i)
                self.graphse.append(graph.grapherror)
                if self.json:
                    if not self.json.endswith('.json'):
                        self.json = json + '.json'
                    myjson.update({
                        graph.legend: {
                            results.GetParameterName(i): results.GetParams()[i]
                            for i in range(results.NPar())
                        }
                    })
            self.Add(graph.graph)
            self.leg.AddEntry(graph.graph, graph.legend, graph.legendOpt)

        f1 = open(self.json, 'a')
        print >> f1, json.dumps(myjson, indent=4)

        f1.close()
Ejemplo n.º 41
0
def findMonster(image, monsterStruct):
    def isMatch(mask, toCheck):
        for (x, y) in zip(mask, toCheck):
            if x == '#' and y == '.':
                return False
        return True

    res = 0
    for flip, rotate in tileCombi:
        modImage = modified(dc(image), flip, rotate)
        for rowIdx, row in enumerate(modImage[1:-1]):
            for offset in range(len(modImage) - len(monsterImg[1])):
                if isMatch(monsterImg[1], row[offset:]) and \
                 isMatch(monsterImg[0], modImage[rowIdx][offset:]) and \
                 isMatch(monsterImg[2], modImage[rowIdx+2][offset:]):
                    res += 1
    return res
Ejemplo n.º 42
0
def get_src_trace(detailed_config, out_folder):
    # process the cmd
    trace_cmd = detailed_config['trace_cmd']
    poc = detailed_config['poc']
    replace_idx = np.where(np.asarray(trace_cmd) == '***')[0]
    cmd = dc(trace_cmd)
    replace_num = len(replace_idx)
    for id in range(replace_num):
        cmd[replace_idx[id]] = poc[id]
    # write the cmd
    cmd_path = os.path.join(out_folder, 'cmd.txt')
    utils.write_txt(cmd_path, [' '.join(cmd)])
    # get binary path
    bin_path = detailed_config['bin_path']
    # get the source trace
    tmp_folder = './tempDr'
    if not os.path.exists(tmp_folder):
        os.mkdir(tmp_folder)
    my_parser = parse_dwarf.DwarfParser(bin_path)
    flineNumberDict, fileBoundRangesList, fileBoundIndexList, src_filepath = my_parser.get_main_addr(
    )
    ifSrcList = tracer.findIfSrcInOrderDyn(bin_path,
                                           src_filepath,
                                           flineNumberDict,
                                           fileBoundRangesList,
                                           fileBoundIndexList,
                                           cmdFile=cmd_path)
    logging.info("Got the source trace!")
    # process the source trace
    insn2src = {}
    src2insn = {}
    for item in ifSrcList:
        insn = item[0]
        src = '-'.join(item[1:3])
        if insn not in insn2src:
            insn2src[insn] = src
        if src in src2insn:
            src2insn[src].add(insn)
        else:
            src2insn[src] = {insn}
    info = {'raw': ifSrcList, 'insn2src': insn2src, 'src2insn': src2insn}
    # write the source trace
    output_path = os.path.join(out_folder, 'poc_source_trace.pkl')
    utils.write_pkl(output_path, info)
    logging.info("Recorded the source trace -> %s" % output_path)
    return insn2src, src2insn
Ejemplo n.º 43
0
 def exploit_explore(self):
     #EXPLOIT/EXPLOIT: Truncation Selection/Perturb
     ranks = self.ranker()#Gives indicies from best to worst score
     num = int(np.ceil(0.2*self.pop_size))
     best = ranks[:num]
     worst = ranks[-num:]
     for idx in range(num):
         self.population[worst[idx]].model.model.set_weights(self.population[best[idx]].model.model.get_weights())
         
         new_hyperparameters = dc(self.population[best[idx]].config['hyperparameters'])
         if np.random.uniform() < 0.5:
             factor = self.explore[0]
         else:
             factor = self.explore[1]
         for param,value in new_hyperparameters.items():
                 new_hyperparameters[param] = value * factor
         self.population[worst[idx]].model.set_hyperparameters(**new_hyperparameters)
Ejemplo n.º 44
0
    def step(self, action, action_type='swap', state=None, rewire_edges=True):

        if state is None:
            state = self.g

        if action_type == 'swap':
            i, j = action
            if i + j == 0:
                return state, torch.tensor(.0)

            old_S = self.calc_S(g=state)
            # swap two nodes
            tmp = dc(state.nodes[i].data['label'])
            state.nodes[i].data['label'] = state.nodes[j].data['label']
            state.nodes[j].data['label'] = tmp

            # rewire edges
            if rewire_edges:
                state.edata['e_type'][:, 1] = torch.mm(state.ndata['label'], state.ndata['label'].t()).view(-1)[
                    self.graph_generator.nonzero_idx]

        elif action_type == 'flip':
            i = action[0]
            target_label = action[1]
            i_label = state.nodes[i].data['label'].argmax().item()

            if i_label == target_label or i + target_label < 0:
                return state, torch.tensor(.0)

            old_S = self.calc_S(g=state)

            # flip node
            state.nodes[i].data['label'] = torch.nn.functional.one_hot(torch.tensor([target_label]), self.k).float()

            # rewire edges
            if rewire_edges:
                state.edata['e_type'][:, 1] = torch.mm(state.ndata['label'], state.ndata['label'].t()).view(-1)[
                    self.graph_generator.nonzero_idx]

        new_S = self.calc_S(g=state)
        reward = old_S - new_S

        if state is None:
            self.S -= reward

        return state, reward
Ejemplo n.º 45
0
def main():
    with open('day22.txt', 'r') as f:
        data = f.read()

    decks = []
    for player in data.split("\n\n"):
        deck = dq()
        player = player.split("\n")
        for line in player:
            if not "Player" in line:
                deck.appendleft(int(re.search(r'\d+', line).group()))
        decks.append(deck)

    _, d = play(dc(decks))
    print("P1: {}".format(score(d)))
    _, d = playtwo(decks)
    print("P2: {}".format(score(d)))
Ejemplo n.º 46
0
async def on_guild_join(guild=None):
    global configs
    # deepcopy because it if not its going to make copies and send more than one more time in one guild
    configs.update({"a" + str(guild.id): dc(defaultconfigs)})
    # Log join guild
    logging.info("Joined guild {} at {}".format(
        guild.id,
        datetime.datetime.now().strftime("%x %X:%f")))
    # Send guild
    await [
        i for i in guild.channels if type(i) == discord.TextChannel
    ][0].send(
        "Thanks for inviting me to the channel.\n Please type `>help` to see what I can do!"
    )
    # update configs
    generalconfigs()
    return
Ejemplo n.º 47
0
 def remove_preseason_games(self, args=None ):
     '''This function removes preseason games based on the start of the season
     arguments:
         args - This should contain a start date that is a datetime.datetime object. defaults to None
     '''
     if args == None:
         start = self.args['start']
     games1 = self.games
     games2 = dc(games1)
     print "len of list one is {0} and len of list two is {1}".format(len(games1), len(games2))
     for i in range(0, len(games1)):       
         for j in range(0, len(games1[0])):
             game = games1[i][j]
             if game.date < start:
                 games2.pop(0)
                 break
     self.games = games2
Ejemplo n.º 48
0
 def number_of_dependency_tags(self, sent):
     """
     Find a dependency tag for each token within a sentence and add their amount
     to a dictionary, depending how many times that particular tag appears.
     """
     dep_dict = dc(self.dep_dict)
     
     for token in sent:
         if token.dep_ == '':
             dep_dict['TRAILING_DEP'] += 1
         else:
             try:
                 dep_dict[token.dep_] += 1
             except:
                 print('Unknown dependency for token: "' + token.orth_ +'". Passing.')
         
     return dep_dict
Ejemplo n.º 49
0
 def removeHorizontalSeam(self, seam):  # function the will remove the seam
     if (seam == None):  # exception handling
         raise ValueError("Seam argument is null")
     imgArr = np.array(self.image, dtype='int64')  # image to array
     if (self.image.size[1] == 1):  # exception handling
         raise ValueError("Current height of image is 1")
     newArr = dc(
         imgArr[:-1])  # new array made with 1 pixel less in the height
     for i in range(
             len(newArr[0])
     ):  # each pixel is copied to the new array except the one in the seam
         for j in range(seam[i]):
             newArr[j][i] = imgArr[j][i]
         for j in range(seam[i], len(newArr)):
             newArr[j][i] = imgArr[j + 1][i]
     self.image = Image.fromarray(
         newArr.astype('uint8'))  # the image is updated
    def EvalData(self, data):
        eData = False
        log("Server", 'EvalData', repr(data))

        try:
            eData = dc(json.loads(data))
        except:
            err1 = sys.exc_info()
            try:
                eData = eval(data)
            except:
                PE("Server", "EvalData", "Error 1", err1, "Error 2",
                   sys.exc_info())
                eData = False
        finally:
            if eData:
                self.DataReadThread(eData)
Ejemplo n.º 51
0
    def check_direction(self, start, dir):
        end = (start[0] + dir[0], start[1] + dir[1])
        board = dc(self.game_board)
        if start[0] < 0 or start[0] > self.board_size or end[0] <= 0 or end[0] >= self.board_size - 1 \
                or start[1] < 0 or start[1] > self.board_size or end[1] <= 0 or end[1] >= self.board_size - 1:
            return -1, []

        # swap
        board[start[0]][start[1]], board[end[0]][end[1]] = board[end[0]][
            end[1]], board[start[0]][start[1]]
        score_start, start_board = self.evaluate_board(start, end, board)
        score_end, end_board = self.evaluate_board(end, start, board)

        if score_start > score_end:
            return score_start, [start, end]
        else:
            return score_end, [end, start]
Ejemplo n.º 52
0
 def get_teeth_neol_chances(self, drawn_teeth):
     """
     Method to return the chance to keep the teeth
     failing order from initialisation to neol
     """
     chances = np.ones((self.no_teeth))
     # Get initial Order of teeth
     teeth_init_order = dc(self.state0['tooth'].to_list())
     teeth_init_order = pd.Series(teeth_init_order)
     # Check if tooth already drawn
     for i, tooth_i in enumerate(teeth_init_order):
         if tooth_i in drawn_teeth:
             chances[i] = 0
     # Get current number of teeth remaining
     tooth_i = len(drawn_teeth)
     chances[tooth_i] = chances[tooth_i] * self.keeporder_chance
     return (np.array(chances))
Ejemplo n.º 53
0
def vis_g(problem, k=None, name='test', topo='knn'):
    plt.figure()

    if isinstance(problem, dgl.DGLGraph):
        g = problem
        k = k
    else:
        k = problem.k
        g = problem.g
    X = g.ndata['x'].cpu()
    n = X.shape[0]
    label = g.ndata['label'].cpu()
    link = dc(g.edata['e_type'].view(n, n - 1, 2).cpu())
    # c = ['r', 'b', 'y']
    plt.cla()
    c = ['r', 'b', 'y', 'k', 'g', 'c', 'm', 'tan', 'peru', 'pink']
    for i in range(k):
        a = X[(label[:, i] > 0).nonzero().squeeze()]
        if a.shape[0] > .5:
            a = a.view(-1, 2)
            plt.scatter(a[:, 0], a[:, 1], s=60, c=[c[i]] * (n // k))

    for i in range(n):
        plt.annotate(str(i), xy=(X[i, 0], X[i, 1]))
        for j in range(n - 1):
            if link[i, j][0].item() == 1:
                j_ = j
                if j >= i:
                    j_ = j + 1
                plt.plot([X[i, 0], X[j_, 0]], [X[i, 1], X[j_, 1]],
                         ':',
                         color='k')

        if topo == 'cut':
            for j in range(n - 1):
                if link[i, j][1].item() + link[i, j][0].item() > 1.5:
                    j_ = j
                    if j >= i:
                        j_ = j + 1
                    plt.plot([X[i, 0], X[j_, 0]], [X[i, 1], X[j_, 1]],
                             '-',
                             color='k')

    plt.savefig(name + '.png')
    plt.close()
Ejemplo n.º 54
0
 def expand_field(field: list[list[list[bool]]]):
     step = dc(field)
     outer = dc(step[0])
     for i, _ in enumerate(outer):
         for j, _ in enumerate(outer[i]):
             outer[i][j] = False
     step.insert(0, dc(outer))
     step.append(dc(outer))
     line = dc(step[0][0])
     for z in step:
         z.insert(0, dc(line))
         z.append(dc(line))
         for y in z:
             y.insert(0, False)
             y.append(False)
     return step
Ejemplo n.º 55
0
 def getState(self, PLowSat, PHighSat, P, T):
     """
     For Rankine, we exit pump at P=PHigh, T4=T3=Tsat for PLow.
     #case 1: PLow<=P<=PHigh
     For the states between P=PLow to PHigh, T=T3: h=h3+(P-PLow)*v3, v=v3 (i.e., incompressible), s=s3 (i.e., isentropic efficiency of pump = 1.0)
     #case 2: P=PHigh, T3<=T<=T5
     Between states (P=PHigh, T4) to (P=PHigh, T5=Tsat,PHigh), I will assume P and T vary linearly, so:
         z=(T-T4)/(T5-T4)
         h4=h3+(PHigh-PLow)v3
         h5, s5, v5=hf, sf, vf for PHigh
         h=h4 +(h5-h4)*z
         s=s3+(s5-s3)*z
         v=v3+(v5-v3)*z
     general function to retrieve the thermodynamic state object (TSat, P, h, s, v)
     :param PLow: in kPa
     :param PHigh: in kPa
     :param P: in kPa
     :param T: in C
     :return: a deep copy of a thermodynamic state object
     """
     state=stateProps()
     case = 1 if (T<=PLowSat.Tsat) else 2
     if case ==1:
         z=(P-PLowSat.Psat)/(PHighSat.Psat-PLowSat.Psat)
         state.h=PLowSat.hf+z*(PHighSat.Psat-PLowSat.Psat)*PLowSat.vf
         state.s=PLowSat.sf
         state.v=PLowSat.vf
         state.T=PLowSat.Tsat
         state.P=P
     else:
         z=(T-PLowSat.Tsat)/(PHighSat.Tsat-PLowSat.Tsat)
         h4=PLowSat.hf+(PHighSat.Psat-PLowSat.Psat)*PLowSat.vf
         s4=PLowSat.sf
         v4=PLowSat.vf
         h5=PHighSat.hf
         s5=PHighSat.sf
         v5=PHighSat.vf
         state.h=h4+z*(h5-h4)
         state.s=s4+z*(s5-s4)
         state.v=v4+z*(v5-v4)
         state.P=P
         state.T=T
     name='subcooled'
     state.x=-0.1
     return dc(state)
Ejemplo n.º 56
0
    def getState(self, P_Bar=None, P_kPa=None, T=None, h=None, s=None, v=None, x=None):
        """
        general function to retrieve the thermodynamic state object (TSat, PSat, h, s, v)
        For this to work properly, need to give a (pressure or a temperature) + one other property
        :param P: pressure in bar (but output in kPa)
        :param T: temperature in C
        :param h: specific enthalpy in kJ/kg
        :param s: specific entropy in kJ/kg*K
        :param v: specific volume in m^3/kg
        :param x: quality
        :return: a thermodynamic state object
        """
        state = stateProps()
        state.region = 'saturated'
        sats=satProps()

        if P_Bar is not None:
            sats = self.getSatProps(P_Bar=P_Bar)
        if P_kPa is not None:
            sats=self.getSatProps(P_kPa=P_Bar)
        if T is not None:
            sats = self.getSatProps(T=T)
        state.P = sats.Psat
        state.T = sats.Tsat
        if h is not None:
            state.h = h
            state.x = (state.h - sats.hf) / sats.hgf
            state.s = sats.sf + state.x * sats.sgf
            state.v = sats.vf + state.x * sats.vgf
        elif s is not None:
            state.s = s
            state.x = (state.s - sats.sf) / sats.sgf
            state.h = sats.hf + state.x * sats.hgf
            state.v = sats.vf + state.x * sats.vgf
        elif v is not None:
            state.v = v
            state.x = (state.v - sats.vf) / sats.vgf
            state.h = sats.hf + state.x * sats.hgf
            state.s = sats.sf + state.x * sats.sgf
        elif x is not None:
            state.x = x
            state.h = sats.hf + state.x * sats.hgf
            state.s = sats.sf + state.x * sats.sgf
            state.v = sats.vf + state.x * sats.vgf
        return dc(state)
Ejemplo n.º 57
0
 def __init__(self, h):  # initialization using a hamiltonian
     self.heff = None  # effective hamiltonian
     self.right_intra = h.intra  # intraterm in the right lead
     self.right_inter = h.inter  # interterm in the right lead (to the right)
     self.right_green = None  # right green function
     self.left_intra = h.intra  # intraterm in the left lead
     self.left_inter = h.inter.H  # interterm in the left lead (to the left)
     self.left_green = None  # left green function
     self.central_intra = h.intra  # intraterm in the center
     self.right_coupling = h.inter  # coupling from the center to the right lead
     self.left_coupling = h.inter.H  # coupling from the center to the left lead
     # geometry of the central part
     gc = dc(h.geometry)
     #    gc.set_finite()
     self.central_geometry = gc  # geometry of the central part
     # additional degrees of freedom
     self.has_spin = h.has_spin  # spin degree of freedom
     self.has_eh = h.has_eh  # electron hole pairs
Ejemplo n.º 58
0
def test_save_load_basevae(invariances):
    data_dim = (5, 8, 8)
    coord = 0
    if invariances is not None:
        coord = len(invariances)
        if 't' in invariances:
            coord = coord + 1
    vae = models.base.baseVAE()
    encoder_net = nets.fcEncoderNet(data_dim[1:], 2 + coord, 0)
    dnet = nets.sDecoderNet if 0 < coord < 5 else nets.fcDecoderNet
    decoder_net = dnet(data_dim, 2, 0)
    vae.set_encoder(encoder_net)
    vae.set_decoder(decoder_net)
    weights_init = dc(vae.state_dict())
    vae.save_weights("my_weights")
    vae.load_weights("my_weights.pt")
    weights_loaded = vae.state_dict()
    assert_(assert_weights_equal(weights_loaded, weights_init))
Ejemplo n.º 59
0
 def Load(self, fInfo):
     res = self.File.Load(fInfo)
     if res:
         lineNum = 0
         for i, line in enumerate(res):
             if line == '*'*50+'\n': lineNum = i+4
         res = res[lineNum:]
         fileLen = len(res)
         for i in range(fileLen):
             items = res.pop(0).strip()
             if not items: continue
             items = items.split(' '*5)
             itemLen = len(items)
             res += [[]]
             for i in range(itemLen):
                 item = items.pop(0).strip()
                 if item: res[len(res)-1] += [item]
     return dc(res)
Ejemplo n.º 60
0
 def Save(self, saveInfo, saveList):
     saveList = dc(saveList)
     writeString = ''
     if saveList and saveList != self.Load(saveInfo[0]):
         minSpace = 5
         saveList.insert(0, ['Source', 'Class', 'Type', 'Target'])
         maxLen = [minSpace*2]*len(saveList[0])
         for line in saveList:
             maxLen = [max(maxLen[i], len(item)) for i, item in enumerate(line)]
         saveList.insert(1, ['-'*(i+minSpace) for i in maxLen])
         writeString = '\n'+('*'*50)+'\n\n'
         for items in saveList:
             for i, item in enumerate(items):
                 writeString += item+' '*((maxLen[i]-len(item))+minSpace) \
                                 if item != '-'*(maxLen[i]+minSpace) else item
             writeString += '\n'
         writeString += '\n'
     self.File.Save(saveInfo, writeString)