コード例 #1
0
ファイル: FATD.py プロジェクト: kkroy36/NIPS
 def getSample(self):
     '''gets a sample trajectory from
        the specified domain
     '''
     d = Chain()
     if self.domain == "blackjack":
         d = Game()
     elif self.domain == "wumpus":
         d = Grid(4)
     elif self.domain == "blocksworld":
         d = BW(4)
     elif self.domain == "traffic":
         d = TrafficSignal()
     elif self.domain == "pong":
         d = Pong()
     elif self.domain == "tetris":
         d = Tetris()
     #elif wumpus
     sample = []
     state = d
     actions = d.actions
     while True:
         if state == "winner" or state == "loser":
             sample += [deepcopy(state)]
             break
         sample += [deepcopy(str(state))]
         action = actions[randint(0,len(actions)-1)]
         state = d.takeAction(state,action)
     return sample
コード例 #2
0
    def init_chain(self, chain_id):
        """Initiate a new Chain object with given id.

        Arguments:
        o chain_id - string
        """
        if self.model.has_id(chain_id):
            self.chain = self.model[chain_id]
            warnings.warn(
                "WARNING: Chain %s is discontinuous at line %i." %
                (chain_id, self.line_counter), PDBConstructionWarning)
        else:
            self.chain = Chain(chain_id)
            self.model.add(self.chain)
コード例 #3
0
    def init_chain(self, chain_id):
        """Initiate a new Chain object with given id.

        Arguments:
        o chain_id - string
        """
        if self.model.has_id(chain_id):
            self.chain = self.model[chain_id]
            if __debug__:
                sys.stderr.write(
                    "WARNING: Chain %s is discontinuous at line %i.\n" %
                    (chain_id, self.line_counter))
        else:
            self.chain = Chain(chain_id)
            self.model.add(self.chain)
コード例 #4
0
ファイル: FATD.py プロジェクト: kkroy36/NIPS
 def __init__(self,FA="LSReg",domain="50chain",N=100,loss="ls",trees=500,type="max",depth=2):
     '''class constructor'''
     self.domain = domain
     if domain == "50chain":
         self.domObj = Chain()
     elif domain == "blackjack":
         self.domObj = Game()
     elif domain == "wumpus":
         self.domObj = Grid(4)
     elif domain == "blocksworld":
         self.domObj = BW(4)
     elif domain == "traffic":
         self.domObj = TrafficSignal()
     elif domain == "pong":
         self.domObj = Pong()
     elif domain == "tetris":
         self.domObj = Tetris()
     if FA == "LSReg":
         self.FA = LSReg()
     elif FA == "NN":
         self.FA = NeuralNetwork()
     elif FA == "GB":
         self.FA = GradientBooster(loss=loss,trees=trees,depth=depth)
     self.value,self.count = {},{}
     self.values = [{} for i in range(N)]
     self.approxValues = [{} for i in range(N)]
     self.BE = []
     self.type = type
     self.TD(self.FA,N)
コード例 #5
0
    def __init__(self, spec):
        Chain.__init__(self)
        assert (spec["Type"] == "MultiLevel")
        self.ChainSpec = spec["Chain"]
        self.Licenses = spec["Licenses"]
        for lic in self.Licenses:
            lic["Count"] = lic["MaxCount"]
        self.Tasks = {}
        for i, taskSpec in enumerate(spec["Tasks"]):
            if self.FindTaskInChain(taskSpec["Name"]) == None:
                print "MultiLevelChain: Task %s not referenced in the chain, skipping it" % taskSpec[
                    "Name"]
                continue
            task = Tasks.Create(self, taskSpec)
            task.ID = i + 1
            self.Tasks[task.Name] = task

        Chain.Initialize(self)
コード例 #6
0
    def init_chain(self, chain_id):
        """Initiate a new Chain object with given id.

        Arguments:
        o chain_id - string
        """
        if self.model.has_id(chain_id):
            self.chain=self.model[chain_id]
            warnings.warn("WARNING: Chain %s is discontinuous at line %i."
                          % (chain_id, self.line_counter),
                          PDBConstructionWarning)
        else:
            self.chain=Chain(chain_id)
            self.model.add(self.chain)
コード例 #7
0
    def init_chain(self, chain_id):
        """Initiate a new Chain object with given id.

        Arguments:
        o chain_id - string
        """
        if self.model.has_id(chain_id):
            self.chain=self.model[chain_id]
            if __debug__:
                sys.stderr.write("WARNING: Chain %s is discontinuous at line %i.\n" 
                        % (chain_id, self.line_counter))
        else:
            self.chain=Chain(chain_id)
            self.model.add(self.chain)
コード例 #8
0
    def build_chains(self):
        chains = {}
        for residue in self.residues:
            if residue.chain_id not in chains:
                chains[residue.chain_id] = Chain(residue.chain_id)

        for residue in self.residues:
            chains[residue.chain_id].residues.append(residue)

        chainlist = []
        for chain in chains.values():
            chainlist.append(chain.chain_id)
        print("Found ", len(chains.values()), " chains: ", chainlist)
        print("\n")
        return chains.values()
コード例 #9
0
def processSingleRunChain(args=None):

    '''
    Function to run single runChain object
    Setup the run chain object with the args
    '''
    e_handler = EventsHandler()
    runchain = Chain(e_handler)
    e_handler.addObserver(runchain)

    run_num = None
    for k in args['rundetails'].keys():
        run_num = k

    #print 'process is ', mp.current_process().name , ' for run ', run_num

    runchain.commands = args['commands']
    #print 'commands', runchain.commands
    rfolder = args['result_folder']

    initialEvent = SimpleEvent('init', True, {'run':run_num, 'result_folder':rfolder})
    runchain.startChainWithEvent(initialEvent)

    return runchain.getResult()
コード例 #10
0
def test():
    from Connectable import Connectable
    class A(Connectable):
        sockets = {
            'out': ['1'],
            }
        def _update(self):
            self._outputs['1'] = 1
            return
        pass
    a = A()
    
    from Passer import Passer
    class B(Passer):
        sockets = {
            'in': ['1'],
            'out': ['1'],
            }
        pass
    b = B()

    class C(Connectable):
        sockets = {
            'in': ['in3'],
            'out': ['out'],
            }
        def _update(self):
            self._outputs['out'] = self._inputs['in3']
            return
        pass
    c = C()
    
    from Node import Node
    n1 = Node( None, a, '1' )
    n2 = Node( '1', b, '1' )
    n3 = Node( 'in3', c, None )
    
    from Chain import Chain
    ch = Chain()
    ch.append( n1 )
    ch.append( n2 )
    ch.append( n3 )
    
    from Chains import Chains
    cs = Chains()
    cs.add( ch )

    r = Runner()
    r( cs )

    assert c.getOutput( 'out' ) == 1
    return
コード例 #11
0
    def copy(self, db):

        # Copy chains list
        self.chains = np.array([Chain(-1)] * db.num_edges)
        for i in range(0, len(db.chains)):
            self.chains[i].copy(db.chains[i])

        # Copy edges list
        self.edges = deepcopy(db.edges)

        # Copy nodes list
        self.nodes = deepcopy(db.nodes)

        self.num_edges = db.num_edges
        self.rows = db.rows
        self.columns = db.columns
        self.score1 = db.score1
        self.score2 = db.score2
        self.curr_player = db.curr_player
コード例 #12
0
def chain_builder(nouns):
    chains = {}
    word_dict = {}
    for noun in nouns:
        if noun not in word_dict.keys():
            word_dict[noun] = 1
            is_new_chain = True
            
            for chain_key in chains.keys():
                if noun in chains[chain_key].syn_list or noun in chains[chain_key].anto_list or noun in chains[chain_key].hypo_list or noun in chains[chain_key].hyper_list:
                    chains[chain_key].add_word_to_lexical_chain(noun)
                    is_new_chain = False
                    break
                  
            if is_new_chain:
                syn_list, anto_list, hypo_list, hyper_list = get_relationships(noun)
                chains[noun] = Chain(noun, syn_list, anto_list, hypo_list, hyper_list)
        else:
            word_dict[noun] += 1
    return chains, word_dict
コード例 #13
0
import os
import sys

sys.path.append("../src")
from Chain import Chain
from Likelihood_Planck import Likelihood_Planck

# Prepare the likelihoods
likelihoods = ["commander", "CAMspec", "lowlike"]
clik_dir = "/home/torradocacho/codes/stable/planck_likelihood_1303"
lik = Likelihood_Planck(base_folder=clik_dir, likelihoods=likelihoods)

# Prepare the spectra
CHAINS = "/data/misc/torradocacho/chains"
base_folder = os.path.join(CHAINS, "historicas/aaot/gaussN/07_final")
chain = Chain(os.path.join(base_folder, "gaussN_var_c"))
# 2 best fits
best_fit_points = chain.best_fit(how_many=2)

class_folder = "/home/torradocacho/cosmo/code/class_v1.7.2_external_Pk"

# Overall best fit
best_fit_point = best_fit_points[1]
override_params = {
    "command":
    "python " +
    os.path.join(class_folder, "external_Pk/generate_Pk_from_u_gaussN.py")
}
spectrum_bf1 = chain.CMBspectrum_from_point(best_fit_point,
                                            class_folder=class_folder,
                                            override_params=override_params,
コード例 #14
0
import os
import sys

sys.path.append("../src")
from Chain import Chain
from plot_Cl_CMB import plot_Cl_CMB

base_folder = "./chains"
name = "planck_WP"
chain = Chain(os.path.join(base_folder, name))

class_folder = "/home/torradocacho/cosmo/code/class_v1.7.2"
spectrum = chain.CMBspectrum_from_point(chain.best_fit(),
                                        class_folder=class_folder,
                                        verbose=True)

plot_Cl_CMB([spectrum], title="Best fit CMB spectrum")
コード例 #15
0
class StructureBuilder:
    """
    Deals with contructing the Structure object. The StructureBuilder class is used
    by the PDBParser classes to translate a file to a Structure object.
    """
    def __init__(self):
        self.line_counter = 0
        self.header = {}

    def _is_completely_disordered(self, residue):
        "Return 1 if all atoms in the residue have a non blanc altloc."
        atom_list = residue.get_unpacked_list()
        for atom in atom_list:
            altloc = atom.get_altloc()
            if altloc == " ":
                return 0
        return 1

    # Public methods called by the Parser classes

    def set_header(self, header):
        self.header = header

    def set_line_counter(self, line_counter):
        """
        The line counter keeps track of the line in the PDB file that 
        is being parsed.
        
        Arguments:
        o line_counter - int
        """
        self.line_counter = line_counter

    def init_structure(self, structure_id):
        """Initiate a new Structure object with given id.

        Arguments:
        o id - string
        """
        self.structure = Structure(structure_id)

    def init_model(self, model_id):
        """Initiate a new Model object with given id.
        
        Arguments:
        o id - int
        """
        self.model = Model(model_id)
        self.structure.add(self.model)

    def init_chain(self, chain_id):
        """Initiate a new Chain object with given id.

        Arguments:
        o chain_id - string
        """
        if self.model.has_id(chain_id):
            self.chain = self.model[chain_id]
            if __debug__:
                sys.stderr.write(
                    "WARNING: Chain %s is discontinuous at line %i.\n" %
                    (chain_id, self.line_counter))
        else:
            self.chain = Chain(chain_id)
            self.model.add(self.chain)

    def init_seg(self, segid):
        """Flag a change in segid.
        
        Arguments:
        o segid - string
        """
        self.segid = segid

    def init_residue(self, resname, field, resseq, icode):
        """
        Initiate a new Residue object.

        Arguments:
        o resname - string, e.g. "ASN"
        o field - hetero flag, "W" for waters, "H" for 
            hetero residues, otherwise blanc.
        o resseq - int, sequence identifier
        o icode - string, insertion code
        """
        if field != " ":
            if field == "H":
                # The hetero field consists of H_ + the residue name (e.g. H_FUC)
                field = "H_" + resname
        res_id = (field, resseq, icode)
        if field == " ":
            if self.chain.has_id(res_id):
                # There already is a residue with the id (field, resseq, icode).
                # This only makes sense in the case of a point mutation.
                if __debug__:
                    sys.stderr.write(
                        "WARNING: Residue ('%s', %i, '%s') redefined at line %i.\n"
                        % (field, resseq, icode, self.line_counter))
                duplicate_residue = self.chain[res_id]
                if duplicate_residue.is_disordered() == 2:
                    # The residue in the chain is a DisorderedResidue object.
                    # So just add the last Residue object.
                    if duplicate_residue.disordered_has_id(resname):
                        # The residue was already made
                        self.residue = duplicate_residue
                        duplicate_residue.disordered_select(resname)
                    else:
                        # Make a new residue and add it to the already
                        # present DisorderedResidue
                        new_residue = Residue(res_id, resname, self.segid)
                        duplicate_residue.disordered_add(new_residue)
                        self.residue = duplicate_residue
                        return
                else:
                    # Make a new DisorderedResidue object and put all
                    # the Residue objects with the id (field, resseq, icode) in it.
                    # These residues each should have non-blanc altlocs for all their atoms.
                    # If not, the PDB file probably contains an error.
                    if not self._is_completely_disordered(duplicate_residue):
                        # if this exception is ignored, a residue will be missing
                        self.residue = None
                        raise PDBConstructionException(\
                            "Blank altlocs in duplicate residue %s ('%s', %i, '%s')" \
                            % (resname, field, resseq, icode))
                    self.chain.detach_child(res_id)
                    new_residue = Residue(res_id, resname, self.segid)
                    disordered_residue = DisorderedResidue(res_id)
                    self.chain.add(disordered_residue)
                    disordered_residue.disordered_add(duplicate_residue)
                    disordered_residue.disordered_add(new_residue)
                    self.residue = disordered_residue
                    return
        residue = Residue(res_id, resname, self.segid)
        self.chain.add(residue)
        self.residue = residue

    def init_atom(self,
                  name,
                  coord,
                  b_factor,
                  occupancy,
                  altloc,
                  fullname,
                  serial_number=None):
        """
        Initiate a new Atom object.

        Arguments:
        o name - string, atom name, e.g. CA, spaces should be stripped
        o coord - Numeric array (Float0, size 3), atomic coordinates
        o b_factor - float, B factor
        o occupancy - float
        o altloc - string, alternative location specifier
        o fullname - string, atom name including spaces, e.g. " CA "
        """
        residue = self.residue
        # if residue is None, an exception was generated during
        # the construction of the residue
        if residue is None:
            return
        # First check if this atom is already present in the residue.
        # If it is, it might be due to the fact that the two atoms have atom
        # names that differ only in spaces (e.g. "CA.." and ".CA.",
        # where the dots are spaces). If that is so, use all spaces
        # in the atom name of the current atom.
        if residue.has_id(name):
            duplicate_atom = residue[name]
            # atom name with spaces of duplicate atom
            duplicate_fullname = duplicate_atom.get_fullname()
            if duplicate_fullname != fullname:
                # name of current atom now includes spaces
                name = fullname
                if __debug__:
                    sys.stderr.write(
                        "WARNING: atom names %s and %s differ only in spaces at line %i.\n"
                        % (duplicate_fullname, fullname, self.line_counter))
        atom = self.atom = Atom(name, coord, b_factor, occupancy, altloc,
                                fullname, serial_number)
        if altloc != " ":
            # The atom is disordered
            if residue.has_id(name):
                # Residue already contains this atom
                duplicate_atom = residue[name]
                if duplicate_atom.is_disordered() == 2:
                    duplicate_atom.disordered_add(atom)
                else:
                    # This is an error in the PDB file:
                    # a disordered atom is found with a blanc altloc
                    # Detach the duplicate atom, and put it in a
                    # DisorderedAtom object together with the current
                    # atom.
                    residue.detach_child(name)
                    disordered_atom = DisorderedAtom(name)
                    residue.add(disordered_atom)
                    disordered_atom.disordered_add(atom)
                    disordered_atom.disordered_add(duplicate_atom)
                    residue.flag_disordered()
                    if __debug__:
                        sys.stderr.write(
                            "WARNING: disordered atom found with blanc altloc before line %i.\n"
                            % self.line_counter)
            else:
                # The residue does not contain this disordered atom
                # so we create a new one.
                disordered_atom = DisorderedAtom(name)
                residue.add(disordered_atom)
                # Add the real atom to the disordered atom, and the
                # disordered atom to the residue
                disordered_atom.disordered_add(atom)
                residue.flag_disordered()
        else:
            # The atom is not disordered
            residue.add(atom)

    def set_anisou(self, anisou_array):
        "Set anisotropic B factor of current Atom."
        self.atom.set_anisou(anisou_array)

    def set_siguij(self, siguij_array):
        "Set standard deviation of anisotropic B factor of current Atom."
        self.atom.set_siguij(siguij_array)

    def set_sigatm(self, sigatm_array):
        "Set standard deviation of atom position of current Atom."
        self.atom.set_sigatm(sigatm_array)

    def get_structure(self):
        "Return the structure."
        # first sort everything
        # self.structure.sort()
        # Add the header dict
        self.structure.header = self.header
        return self.structure

    def set_symmetry(self, spacegroup, cell):
        pass
コード例 #16
0
from Chain import Chain
from flask import Flask, render_template, request
app = Flask(__name__)

my_chain = Chain()


@app.route("/")
@app.route("/home")
def home():
    return render_template("home.html", blocks=my_chain.block_chain)


#to add a transaction "/add?tx=some-transaction"
@app.route("/add")
def add():
    query = request.args.get('tx')
    my_chain.add_data(query)
    return render_template("add.html", query=query, message="query added")


@app.route("/mine")
def mine():
    message = my_chain.create_block()
    return render_template("mine.html", message=message)


if __name__ == '__main__':
    app.run(debug=True)
コード例 #17
0
import os
import sys

sys.path.append("../src")
from Chain import Chain
from plot_Cl_CMB import plot_Cl_CMB

base_folder = "./chains"
name = "planck_WP"
chain = Chain(os.path.join(base_folder, name))

class_folder = "/home/torradocacho/cosmo/code/class_v1.7.2"
spectrum = chain.CMBspectrum_from_point(chain.best_fit(),
                                        class_folder=class_folder,
                                        verbose=True)

plot_Cl_CMB([spectrum], title = "Best fit CMB spectrum")
コード例 #18
0
def chain():
    from Chain import Chain
    return Chain()
コード例 #19
0
import os
import sys

sys.path.append("../src")
from Chain import Chain
from plot_lik import plot_lik_2D

base_folder = "./chains"
chain_name = "planck_WP"
chain = Chain(os.path.join(base_folder, chain_name))

labels = {"omega_b":   r"$\omega_\mathrm{B}$",
          "omega_cdm": r"$\omega_\mathrm{C}$",
          "H0":        r"$H_0$",
          "tau_reio":  r"$\tau_\mathrm{reio}$",
          "A_s":       r"$A_s$",
          "n_s":       r"$n_s$",}
chain.set_parameter_labels(labels)
chain.plot_correlation(params = labels.keys(), save_file="correlations.png")
コード例 #20
0
class StructureBuilder:
    """
    Deals with contructing the Structure object. The StructureBuilder class is used
    by the PDBParser classes to translate a file to a Structure object.
    """
    def __init__(self):
        self.line_counter=0
        self.header={}

    def _is_completely_disordered(self, residue):
        "Return 1 if all atoms in the residue have a non blank altloc."
        atom_list=residue.get_unpacked_list()
        for atom in atom_list:
            altloc=atom.get_altloc()
            if altloc==" ":
                return 0
        return 1

    # Public methods called by the Parser classes

    def set_header(self, header):
        self.header=header

    def set_line_counter(self, line_counter):
        """
        The line counter keeps track of the line in the PDB file that 
        is being parsed.
        
        Arguments:
        o line_counter - int
        """
        self.line_counter=line_counter

    def init_structure(self, structure_id):
        """Initiate a new Structure object with given id.

        Arguments:
        o id - string
        """
        self.structure=Structure(structure_id)

    def init_model(self, model_id):
        """Initiate a new Model object with given id.
        
        Arguments:
        o id - int
        """
        self.model=Model(model_id)
        self.structure.add(self.model)

    def init_chain(self, chain_id):
        """Initiate a new Chain object with given id.

        Arguments:
        o chain_id - string
        """
        if self.model.has_id(chain_id):
            self.chain=self.model[chain_id]
            if __debug__:
                warnings.warn("WARNING: Chain %s is discontinuous at line %i."
                              % (chain_id, self.line_counter),
                              PDBConstructionWarning)
        else:
            self.chain=Chain(chain_id)
            self.model.add(self.chain)

    def init_seg(self, segid):
        """Flag a change in segid.
        
        Arguments:
        o segid - string
        """
        self.segid=segid

    def init_residue(self, resname, field, resseq, icode):
        """
        Initiate a new Residue object.

        Arguments:
        o resname - string, e.g. "ASN"
        o field - hetero flag, "W" for waters, "H" for 
            hetero residues, otherwise blank.
        o resseq - int, sequence identifier
        o icode - string, insertion code
        """
        if field!=" ":
            if field=="H":
                # The hetero field consists of H_ + the residue name (e.g. H_FUC)
                field="H_"+resname 
        res_id=(field, resseq, icode) 
        if field==" ":
            if self.chain.has_id(res_id):
                # There already is a residue with the id (field, resseq, icode).
                # This only makes sense in the case of a point mutation.
                if __debug__:
                    warnings.warn("WARNING: Residue ('%s', %i, '%s') "
                                  "redefined at line %i."
                                  % (field, resseq, icode, self.line_counter),
                                  PDBConstructionWarning)
                duplicate_residue=self.chain[res_id]
                if duplicate_residue.is_disordered()==2:
                    # The residue in the chain is a DisorderedResidue object.
                    # So just add the last Residue object. 
                    if duplicate_residue.disordered_has_id(resname):
                        # The residue was already made
                        self.residue=duplicate_residue
                        duplicate_residue.disordered_select(resname)
                    else:
                        # Make a new residue and add it to the already
                        # present DisorderedResidue
                        new_residue=Residue(res_id, resname, self.segid)
                        duplicate_residue.disordered_add(new_residue)
                        self.residue=duplicate_residue
                        return
                else:
                    # Make a new DisorderedResidue object and put all
                    # the Residue objects with the id (field, resseq, icode) in it.
                    # These residues each should have non-blank altlocs for all their atoms.
                    # If not, the PDB file probably contains an error. 
                    if not self._is_completely_disordered(duplicate_residue):
                        # if this exception is ignored, a residue will be missing
                        self.residue=None
                        raise PDBConstructionException(\
                            "Blank altlocs in duplicate residue %s ('%s', %i, '%s')" \
                            % (resname, field, resseq, icode))
                    self.chain.detach_child(res_id)
                    new_residue=Residue(res_id, resname, self.segid)
                    disordered_residue=DisorderedResidue(res_id)
                    self.chain.add(disordered_residue)
                    disordered_residue.disordered_add(duplicate_residue)
                    disordered_residue.disordered_add(new_residue)
                    self.residue=disordered_residue
                    return
        residue=Residue(res_id, resname, self.segid)
        self.chain.add(residue)
        self.residue=residue

    def init_atom(self, name, coord, b_factor, occupancy, altloc, fullname,
                  serial_number=None, element=None):
        """
        Initiate a new Atom object.

        Arguments:
        o name - string, atom name, e.g. CA, spaces should be stripped
        o coord - Numeric array (Float0, size 3), atomic coordinates
        o b_factor - float, B factor
        o occupancy - float
        o altloc - string, alternative location specifier
        o fullname - string, atom name including spaces, e.g. " CA "
        o element - string, upper case, e.g. "HG" for mercury
        """
        residue=self.residue
        # if residue is None, an exception was generated during
        # the construction of the residue
        if residue is None:
            return
        # First check if this atom is already present in the residue. 
        # If it is, it might be due to the fact that the two atoms have atom 
        # names that differ only in spaces (e.g. "CA.." and ".CA.",
        # where the dots are spaces). If that is so, use all spaces
        # in the atom name of the current atom. 
        if residue.has_id(name):
                duplicate_atom=residue[name]
                # atom name with spaces of duplicate atom
                duplicate_fullname=duplicate_atom.get_fullname()
                if duplicate_fullname!=fullname:
                    # name of current atom now includes spaces
                    name=fullname
                    if __debug__:
                        warnings.warn("WARNING: atom names %s and %s differ "
                                      "only in spaces at line %i."
                                      % (duplicate_fullname, fullname,
                                         self.line_counter),
                                      PDBConstructionWarning)
        atom=self.atom=Atom(name, coord, b_factor, occupancy, altloc,
                            fullname, serial_number, element)
        if altloc!=" ":
            # The atom is disordered
            if residue.has_id(name):
                # Residue already contains this atom
                duplicate_atom=residue[name]
                if duplicate_atom.is_disordered()==2:
                    duplicate_atom.disordered_add(atom)     
                else:
                    # This is an error in the PDB file:
                    # a disordered atom is found with a blank altloc
                    # Detach the duplicate atom, and put it in a 
                    # DisorderedAtom object together with the current 
                    # atom.
                    residue.detach_child(name)
                    disordered_atom=DisorderedAtom(name)
                    residue.add(disordered_atom)
                    disordered_atom.disordered_add(atom)
                    disordered_atom.disordered_add(duplicate_atom)
                    residue.flag_disordered()
                    if __debug__:
                        warnings.warn("WARNING: disordered atom found "
                                      "with blank altloc before line %i.\n"
                                      % self.line_counter,
                                      PDBConstructionWarning)
            else:
                # The residue does not contain this disordered atom
                # so we create a new one.
                disordered_atom=DisorderedAtom(name)
                residue.add(disordered_atom)
                # Add the real atom to the disordered atom, and the 
                # disordered atom to the residue
                disordered_atom.disordered_add(atom)
                residue.flag_disordered()
        else:   
            # The atom is not disordered
            residue.add(atom)

    def set_anisou(self, anisou_array):
        "Set anisotropic B factor of current Atom."
        self.atom.set_anisou(anisou_array)

    def set_siguij(self, siguij_array):
        "Set standard deviation of anisotropic B factor of current Atom."
        self.atom.set_siguij(siguij_array)

    def set_sigatm(self, sigatm_array):
        "Set standard deviation of atom position of current Atom."
        self.atom.set_sigatm(sigatm_array)

    def get_structure(self):
        "Return the structure."
        # first sort everything
        # self.structure.sort()
        # Add the header dict
        self.structure.header=self.header
        return self.structure

    def set_symmetry(self, spacegroup, cell):
        pass
コード例 #21
0
ファイル: unpackForTraining.py プロジェクト: ICBPHCMS/BMX
        backgroundFilesBatched.append(
            backgroundFiles[((2 * i + 1) * args.numberOfBatches - b) %
                            len(backgroundFiles)][0])

batchStartBackground = int(
    round(1. * len(backgroundFilesBatched) / args.numberOfBatches *
          args.currentBatchNumber))
batchEndBackground = int(
    round(1. * len(backgroundFilesBatched) / args.numberOfBatches *
          (args.currentBatchNumber + 1)))

print "bkg slice: ", batchStartBackground, "-", batchEndBackground, "/", len(
    backgroundFilesBatched)
#sys.exit(1)
#signalFiles = signalFiles[:10]
signalChain = Chain(map(lambda f: f[0], signalFiles))
backgroundChain = Chain(
    backgroundFilesBatched[batchStartBackground:batchEndBackground])
#backgroundChain = Chain([backgroundFiles[0][0]])#,backgroundFiles[1][0]])

convert(
    args.output,
    signalChain,
    backgroundChain,
    repeatSignal=args.repeatSignal,
    nBatch=args.numberOfBatches,
    batch=args.currentBatchNumber,
    maxCombinations=20,
    maxGenIndex=20,
)
コード例 #22
0
 elif choice == 2:
     os.system('clear')
     print(color['BLUE'] + "[PyBlock:NewChain]" + color['ENDC'])
     print()
     print(color['LGREEN'] + "1." + color['ENDC'] + "New")
     print(color['LGREEN'] + "2." + color['ENDC'] +
           "Copy From Previous Chain")
     print(color['LRED'] + "0." + color['ENDC'] + "Exit")
     print()
     c = int(input(color['LGREEN'] + ">" + color['ENDC']))
     if c == 0:
         continue
     if c == 1:
         name = input("Chain Name" + color['LGREEN'] + ">" +
                      color['ENDC'])
         chains.append(Chain(name))
         print(color['GREEN'] + "New Chain Added" + color['ENDC'])
         save()
     if c == 2:
         idx = int(
             input("Chain Index" + color['LGREEN'] + ">" +
                   color['ENDC']))
         name = input("Chain Name" + color['LGREEN'] + ">" +
                      color['ENDC'])
         try:
             c = chains[idx - 1].fork()
             c.name = name
             chains.append(c)
             print(color['GREEN'] + "New Chain Added" +
                   color['ENDC'])
             save()
コード例 #23
0
import threading, json, time
from Broadcast import Broadcast
import Broadcast as bd
from Chain import Chain, get_lock, release_lock
from chain_utils import get_blocks, append_block
# from Transaction import Broadcast.txnBuffer
from Block import block_size, Block

CH = Chain()

BR = Broadcast()


# broadcast reciever
t1 = threading.Thread(target = BR.recieve_broadcast)

# tcp data reciever
t2 = threading.Thread(target = BR.recieve_data)

# im alive broadcast
t3 = threading.Thread(target = BR.imAlive)

# im alive broadcast
t4 = threading.Thread(target = BR.shareChain)

t1.start()
t2.start()
t3.start()
t4.start()

while True:
コード例 #24
0
    def compute_transfer_model(self):
        X,Y,bk = [],[],[]
        i = 0
        values = {}
        while i < self.transfer+1: #at least one iteration burn in time
            if self.simulator == "logistics":
                state = Logistics(number = self.state_number,start=True)
                if not bk:
                    bk = Logistics.bk
            elif self.simulator == "pong":
                state = Pong(number = self.state_number,start=True)
                if not bk:
                    bk = Pong.bk
            elif self.simulator == "tetris":
                state = Tetris(number = self.state_number,start=True)
                if not bk:
                    bk = Tetris.bk
            elif self.simulator == "wumpus":
                state = Wumpus(number = self.state_number,start=True)
                if not bk:
                    bk = Wumpus.bk
            elif self.simulator == "blocks":
                state = Blocks_world(number = self.state_number,start=True)
                if not bk:
                    bk = Blocks_world.bk
            elif self.simulator == "blackjack":
                state = Game(number = self.state_number,start=True)
                if not bk:
                    bk = Game.bk
            elif self.simulator == "50chain":
                state = Chain(number = self.state_number,start=True)
                if not bk:
                    bk = Chain.bk
            elif self.simulator == "net_admin":
                state = Admin(number = self.state_number,start=True)
                if not bk:
                    bk = Admin.bk
            with open(self.simulator+"_transfer_out.txt","a") as f:
                if self.transfer:
                    f.write("start state: "+str(state.get_state_facts())+"\n")
                time_elapsed = 0
                within_time = True
                start = clock()
                trajectory = [(state.state_number,state.get_state_facts())]
                while not state.goal():
                    if self.transfer:
                        f.write("="*80+"\n")
                    state_action_pair = state.execute_random_action()
                    state = state_action_pair[0] #state
                    if self.transfer:
                        f.write(str(state.get_state_facts())+"\n")
                    trajectory.append((state.state_number,state.get_state_facts()))
                    end = clock()
                    time_elapsed = abs(end-start)
                    if self.simulator == "logistics" and time_elapsed > 0.5:
                        within_time = False
                        break
                    elif self.simulator == "pong" and time_elapsed > 1000:
                        within_time = False
                        break
                    elif self.simulator == "tetris" and time_elapsed > 1000:
                        within_time = False
                        break
                    elif self.simulator == "wumpus" and time_elapsed > 1:
                        within_time = False
                        break
                    elif self.simulator == "blocks" and time_elapsed > 1:
                        within_time = False
                        break
                    elif self.simulator == "blackjack" and time_elapsed > 1:
                        within_time = False
                        break
                    elif self.simulator == "50chain" and time_elapsed > 2:
                        within_time = False
                        break
                    elif self.simulator == "net_admin" and time_elapsed > 1:
                        within_time = False
                        break
                if within_time:
                    self.compute_value_of_trajectory(values,trajectory)
		    self.state_number += len(trajectory)+1
                    for key in values:
                        state = list(key[1])
                        value = values[key]
                        X.append(state)
                        Y.append(value)
                    '''
                    for key in values:
                        facts += list(key[1])
                        example_predicate = "value(s"+str(key[0])+") "+str(values[key])
                        examples.append(example_predicate)
                    '''
                    i += 1
        npX = np.array(X)
        npY = np.array(Y)
	if not self.transfer:
		npY = np.zeros(len(npY))
        model = MLPRegressor(hidden_layer_sizes=(25,),
                             activation="logistic",
                             solver="lbfgs",
                             alpha=0.0001,
                             batch_size="auto",
                             learning_rate="constant",
                             learning_rate_init=0.001,
                             power_t=0.5,
                             max_iter=200,
                             shuffle=True,
                             random_state=None,
                             tol=0.0001,
                             verbose=False,
                             warm_start=False,
                             momentum=0.9,
                             nesterovs_momentum=True,
                             early_stopping=False,
                             validation_fraction=0.1,
                             beta_1=0.9,
                             beta_2=0.999,
                             epsilon=1e-08)
        print (npX)
	model.fit(npX,npY)
        #reg = GradientBoosting(regression = True,treeDepth=2,trees=self.trees,sampling_rate=0.7,loss=self.loss)
        #reg.setTargets(["value"])
        #reg.learn(facts,examples,bk)
        self.model = model
        self.AVI()
コード例 #25
0
    def __init__(self, rows, columns):

        # Get arguments
        self.rows = rows
        self.columns = columns

        # Set initial scores of player 1, 2 = 0
        self.score1 = 0
        self.score2 = 0

        # Set current player to 1
        self.curr_player = 1

        # Numpy array holding the information about the valency of the nodes(coins)
        self.nodes = np.array([4] * ((self.rows) * (self.columns)))

        # Numpy array of each edge. They are indexed from left to right starting from the top
        # The ID of a given edge is its index in the array
        self.num_edges = self.rows * self.columns + (self.rows + 1) * (
            self.columns + 1) - 1
        # the array
        self.edges = np.array([Edge(-1, -1, -1, -1)] * self.num_edges)

        # chains. uses num_edges because the number of edges is the max number of chains
        self.chains = np.array([Chain(-1)] * self.num_edges)

        num_col = self.columns + self.columns + 1  #the number of columns of edges
        num_edge_rows = self.rows + self.rows + 1  #the number of rows of edges
        cur_edge = 0
        ix = 0  #horizontal row count
        iy = 0  #vertical row count

        # Initialize the edge array
        for i in range(0, num_edge_rows):
            #horizontal row
            if i % 2 == 1:
                for j in range(0, self.columns + 1):

                    if j == 0:
                        left_node = -1
                    else:
                        left_node = cur_edge - (self.rows + 1) - (
                            2 * self.rows + 1) * ix + self.rows * ix

                    if j == columns:
                        right_node = -1
                    else:
                        right_node = cur_edge - (self.rows) - (
                            2 * self.rows + 1) * ix + self.rows * ix

                    self.chains[cur_edge] = Chain(cur_edge)
                    self.edges[cur_edge] = Edge(cur_edge, left_node,
                                                right_node, cur_edge)
                    cur_edge += 1
                ix += 1
            #vertical row
            else:
                for j in range(0, self.columns):
                    if i == 0:
                        top_node = -1
                    else:
                        top_node = cur_edge - self.rows - (self.rows + 1) * iy
                    if i == num_edge_rows - 1:
                        bot_node = -1
                    else:
                        bot_node = cur_edge - (self.rows + 1) * iy

                    self.chains[cur_edge] = Chain(cur_edge)
                    self.edges[cur_edge] = Edge(cur_edge, top_node, bot_node,
                                                cur_edge)
                    cur_edge += 1
                iy += 1
コード例 #26
0
import os
import sys

sys.path.append("../src")
from Chain import Chain
from Likelihood_Planck import Likelihood_Planck

# Prepare the likelihoods
likelihoods = ["commander", "CAMspec", "lowlike"]
clik_dir = "/home/torradocacho/codes/stable/planck_likelihood_1303"
lik = Likelihood_Planck(base_folder=clik_dir, likelihoods=likelihoods)

# Prepare the spectra
CHAINS = "/data/misc/torradocacho/chains"
base_folder = os.path.join(CHAINS, "historicas/aaot/gaussN/07_final")
chain = Chain(os.path.join(base_folder, "gaussN_var_c"))
# 2 best fits
best_fit_points = chain.best_fit(how_many=2)

class_folder = "/home/torradocacho/cosmo/code/class_v1.7.2_external_Pk"

# Overall best fit
best_fit_point = best_fit_points[1]
override_params = {"command": "python "+
                   os.path.join(class_folder,
                                "external_Pk/generate_Pk_from_u_gaussN.py")}
spectrum_bf1    = chain.CMBspectrum_from_point(best_fit_point,
                                               class_folder=class_folder,
                                               override_params=override_params,
                                               verbose=True)
override_params = {"P_k_ini type": "analytic_Pk",
コード例 #27
0
                    metavar="List of 2 parameters to plot")
parser.add_argument("-o",
                    "--output",
                    type=str,
                    dest="output",
                    nargs=1,
                    default=None,
                    metavar="Optional file in which to store the plot.")
parser.add_argument("folders",
                    type=str,
                    nargs="+",
                    metavar="Folders of the chains to be plotted.")
args = parser.parse_args()

# Loading the chains
chains = [Chain(folder) for folder in args.folders]

# Plotting
try:
    kwargs = json.loads(args.kwargs)
except ValueError:
    raise ValueError(
        "The dictionary after '-k'/'--keywords' could not be parsed!" +
        " Check the input.")
fig, axarr = plt.subplots(2, 2)
axes_locations = {
    "profile": axarr[0, 1],
    "mean": axarr[1, 0],
    "marginal": axarr[1, 1]
}
for mode, axes in axes_locations.items():
コード例 #28
0
from flask import Flask
from flask import request
from Chain import Chain
from Block import Block
import json

node = Flask(__name__)
blockchain = Chain()
blockchain.start_chain()
i = 0
transaction_queue = [{
    'from': 'matteo',
    'to': 'kevin',
    'value': '3'
}, {
    'from': 'annie',
    'to': 'john',
    'value': '5'
}]
blocks_queue = []


@node.route('/blocks', methods=['GET'])  # mostra blocchi nella blockchain
def blocks():
    chain = blockchain.get_blockchain()
    json_chain = []
    for block in chain:
        dict = {
            'hash': block.hash,
            'id': block.id,
            'transaction': block.transactions
コード例 #29
0
import os
import sys

sys.path.append("../src")
from Chain import Chain
from plot_lik import plot_lik_2D

base_folder = "./chains"
chain_name = "planck_WP"
chain = Chain(os.path.join(base_folder, chain_name))

labels = {
    "omega_b": r"$\omega_\mathrm{B}$",
    "omega_cdm": r"$\omega_\mathrm{C}$",
    "H0": r"$H_0$",
    "tau_reio": r"$\tau_\mathrm{reio}$",
    "A_s": r"$A_s$",
    "n_s": r"$n_s$",
}
chain.set_parameter_labels(labels)
chain.plot_correlation(params=labels.keys(), save_file="correlations.png")
コード例 #30
0
    def AVI(self):
        for i in range(self.number_of_iterations):
            j = 0
            X,Y,bk = [],[],[]
            values = {}
            fitted_values = {}
            while j < self.batch_size:
                if self.simulator == "logistics":
                    state = Logistics(number = self.state_number,start=True)
                    if not bk:
                        bk = Logistics.bk
                elif self.simulator == "pong":
                    state = Pong(number = self.state_number,start=True)
                    if not bk:
                        bk = Pong.bk
                elif self.simulator == "tetris":
                    state = Tetris(number = self.state_number,start=True)
                    if not bk:
                        bk = Tetris.bk
                elif self.simulator == "wumpus":
                    state = Wumpus(number = self.state_number,start=True)
                    if not bk:
                        bk = Wumpus.bk
                elif self.simulator == "blocks":
                    state = Blocks_world(number = self.state_number,start=True)
                    if not bk:
                        bk = Blocks_world.bk
                elif self.simulator == "blackjack":
                    state = Game(number = self.state_number,start=True)
                    if not bk:
                        bk = Game.bk
                elif self.simulator == "50chain":
                    state = Chain(number = self.state_number,start=True)
                    if not bk:
                        bk = Chain.bk
                elif self.simulator == "net_admin":
                    state = Admin(number = self.state_number,start=True)
                    if not bk:
                        bk = Admin.bk
                with open(self.simulator+"_FVI_out.txt","a") as fp:
                    fp.write("*"*80+"\nstart state: "+str(state.get_state_facts())+"\n")
                    time_elapsed = 0
                    within_time = True
                    start = clock()
                    trajectory = [(state.state_number,state.get_state_facts())]
                    while not state.goal():
                        fp.write("="*80+"\n")
                        state_action_pair = state.execute_random_action()
                        state = state_action_pair[0]
                        fp.write(str(state.get_state_facts())+"\n")
                        trajectory.append((state.state_number,state.get_state_facts()))
                        end = clock()
                        time_elapsed = abs(end-start)
                        if self.simulator == "logistics" and time_elapsed > 0.5:
                            within_time = False
                            break
                        elif self.simulator == "pong" and time_elapsed > 1000:
                            within_time = False
                            break
                        elif self.simulator == "tetris" and time_elapsed > 10:
                            within_time = False
                            break
                        elif self.simulator == "wumpus" and time_elapsed > 1:
                            within_time = False
                            break
                        elif self.simulator == "blocks" and time_elapsed > 1:
                            within_time = False
                            break
                        elif self.simulator == "blackjack" and time_elapsed > 1:
                            within_time = False
                            break
                        elif self.simulator == "50chain" and time_elapsed > 1:
                            within_time = False
                            break
                        elif self.simulator == "net_id" and time_elapsed > 1:
                            within_time = False
                    if within_time:
			if i > 0:
                            self.compute_value_of_trajectory(values,trajectory,AVI=True)
                        else:
                            self.compute_value_of_trajectory(values,trajectory,AVI=False)
			self.state_number += 1
                        for key in values:
                            state = list(key[1])
                            value = values[key]
                            #X.append(state)
                            fitted_values[key] = self.model.predict(np.array([state]))
                            #Y.append([value])
                        '''
                        for key in values:
                            facts += list(key[1])
                            example_predicate = "value(s"+str(key[0])+") "+str(values[key])
                            examples.append(example_predicate)
                        '''
                        j += 1
            #fitted_values = self.model.predict(np.array(X))
            bellman_error = self.compute_bellman_error(values,fitted_values)
            with open(self.simulator+"_BEs.txt","a") as f:
                f.write("iteration: "+str(i)+" average bellman error: "+str(bellman_error)+"\n")
            for key in values:
                X.append(list(key[1]))
                Y.append(values[key])
            npX = np.array(X)
            npY = np.array(Y)
            self.model.fit(npX,npY)
コード例 #31
0
ファイル: ChainConcept.py プロジェクト: WalterBejar/catena
        print "Result = %d" % input


###############################################################################
if __name__ == "__main__":

    stringSource1 = StringSource("2")
    stringToInt1 = StringToInt(stringSource1)

    stringSource2 = StringSource("3")
    stringToInt2 = StringToInt(stringSource2)

    multiply = Multiply(
        [stringToInt1, stringToInt2, stringToInt2, stringToInt1])

    intSink = IntSink([stringSource1, multiply])

    Chain.Render(intSink)

    #
    # Errors Detected:
    #
    # connect too many input stages
    # change type of output
    # do not fill output parameter
    # incorrect output type
    # invalid input stage index
    # invalid input stage key (GetInputStageValue)
    # set invalid output parameter
    #
コード例 #32
0
import os
import sys

sys.path.append("../src")
from Chain import Chain
from plot_lik import plot_lik_2D

base_folder = "./chains"
chain = "planck_WP"
chains = [Chain(os.path.join(base_folder, chain))]
params = ["H0", "omega_b"]
labels = [r"$H_0$", r"$\omega_b$"]

modes = ["marginal", "profile"]
for mode in modes:
    plot_lik_2D(mode,
                chains,
                params=params,
                labels=labels,
                format="-loglik",
                save="./%s_%s_%s.png" % (params[0], params[1], mode))
コード例 #33
0
ファイル: main.py プロジェクト: mingmingsuper/PythonTest
#     self.age = age

# student.name = "Lucy"
# student.sex = '男'
student.age = 90
print(student.age)
print(student2.age)
print(student)
# print(student.name)

# 动态绑定方法到实例
# student.set_age = MethodType(set_age, student)
# student.set_age(20)
# print(student.age)

url1 = Chain().users.test
print(url1)

url = Chain().users('mac').photo('testphoto').repos

print(url)


# 使用type创建class
def fn(self, name='world'):
    print('Hello, %s.' % name)


Hello = type('Hello', (object, ), dict(hello=fn))
h = Hello()
h.hello('Mac')