예제 #1
0
    def setUp(self):
        super(BondTestCase, self).setUp()
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()

        self.name = "Bob McBob"
        self.issued_at_epoch = 1528896868
        self.expires_at_epoch = 1529081182
        self.fake_access_token = str(uuid.uuid4())
        self.user_id = str(uuid.uuid4())

        data = {"context": {"user": {"name": self.name}}, 'iat': self.issued_at_epoch}
        encoded_jwt = jwt.encode(data, 'secret', 'HS256')
        fake_token_dict = {FenceKeys.ACCESS_TOKEN_KEY: self.fake_access_token,
                           FenceKeys.REFRESH_TOKEN_KEY: str(uuid.uuid4()),
                           FenceKeys.ID_TOKEN: encoded_jwt,
                           FenceKeys.EXPIRES_AT_KEY: self.expires_at_epoch}

        mock_oauth_adapter = OauthAdapter("foo", "bar", "baz", "qux")
        mock_oauth_adapter.exchange_authz_code = MagicMock(return_value=fake_token_dict)
        mock_oauth_adapter.refresh_access_token = MagicMock(return_value=fake_token_dict)
        mock_oauth_adapter.revoke_refresh_token = MagicMock()

        fence_api = self._mock_fence_api(json.dumps({"private_key_id": "asfasdfasdf"}))
        sam_api = self._mock_sam_api(self.user_id, "email")
        self.bond = Bond(mock_oauth_adapter, fence_api, sam_api,
                         FenceTokenVendingMachine(fence_api, sam_api, mock_oauth_adapter, provider_name),
                         provider_name, "/context/user/name")
예제 #2
0
    def parseBonds(self):
        '''
        read some bond attributes
        '''
        bonds = {}        # dictionary with bond objects, both orientations
        atom_pairs = []   # atom index pairs only, unique

        for bond in self.tkmol.iterateBonds():
            # start, end, bond_type, stereo = numbers
            start = bond.source().index()
            end = bond.destination().index()

            bond_type = bond.bondOrder() # 1,2,3,4 for single, double, triple, aromatic
            stereo = bond.bondStereo()

            start_atom = self.atoms[start]
            end_atom = self.atoms[end]

            bond = Bond(self.options, start_atom, end_atom, bond_type, stereo)

            # we store both orientations of the bond, since we don't know yet
            # which way it will be used
            bonds[(start, end)] = bond
            bonds[(end, start)] = bond.invert()

            atom_pairs.append((start, end))

        return bonds, atom_pairs
예제 #3
0
 def testMakeFromBondsWithSuccess(self):
     b1 = bond = Bond(angleTests.a1, angleTests.a2, 2, None)
     b2 = bond = Bond(angleTests.a2, angleTests.a3, 2, None)
     angle = Angle.makeFromBonds(b1, b2)
     self.assertEqual(angle.get_a_1(), angleTests.a1)
     self.assertEqual(angle.get_a_2(), angleTests.a2)
     self.assertEqual(angle.get_a_3(), angleTests.a3)
예제 #4
0
def test_bond():
    b = Bond(0, 1)
    assert b.get_bond_order() == 1

    b1 = Bond(1, 0)
    assert b == b1

    assert b.get_nbr_atom_idx(1) == 0
예제 #5
0
 def authenticate(bond_hub: Bond) -> bool:
     try:
         bond_hub.getDeviceIds()
         return True
     except RequestConnectionError:
         raise CannotConnect
     except JSONDecodeError:
         return False
예제 #6
0
def test_creation():
    with pytest.raises(ValueError):
        Bond(0, 0)

    with pytest.raises(ValueError):
        Bond(-1, 0)

    with pytest.raises(ValueError):
        Bond(0, -1)
예제 #7
0
    def link_atoms(self, x, y):
        '''
        connect atoms with indexes x and y using a pseudo bond.
        Helper for connect_fragments
        '''
        start_atom = self.atoms[x]
        end_atom = self.atoms[y]

        bond = Bond(self.options, start_atom, end_atom)
        bond.set_link()

        self.bonds[(x, y)] = bond
        self.bonds[(y, x)] = bond.invert()

        start_atom.neighbors.append(y)
        end_atom.neighbors.append(x)
예제 #8
0
def bond_dict_maker(file):
    """
    Creates a dictionary of Bond objects by reading from a .csv file.

    @type file: str
    @rtype: dictionary
    """
    bonds = {}

    with open(file, "r") as f:
        reader = csv.reader(f)
        next(reader, None)
        for row in reader:
            name = row[0]
            typ = row[1]

            # cleaning up data... needs to be in numerical form, so:
            # remove the word "years" from term...
            term = float(row[2].strip(" years"))

            # ... and remove '%' sign from yield
            yld = float(row[3].strip('%'))
            new_bond = Bond(name, typ, term, yld)
            bonds[name] = new_bond

    return bonds
예제 #9
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
    """Set up Bond from a config entry."""
    host = entry.data[CONF_HOST]
    token = entry.data[CONF_ACCESS_TOKEN]

    bond = Bond(bondIp=host, bondToken=token)
    hub = BondHub(bond)
    await hass.async_add_executor_job(hub.setup)
    hass.data[DOMAIN][entry.entry_id] = hub

    device_registry = await dr.async_get_registry(hass)
    device_registry.async_get_or_create(
        config_entry_id=entry.entry_id,
        identifiers={(DOMAIN, hub.bond_id)},
        manufacturer="Olibra",
        name=hub.bond_id,
        model=hub.target,
        sw_version=hub.fw_ver,
    )

    for component in PLATFORMS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, component))

    return True
예제 #10
0
파일: lsimu.py 프로젝트: oeway/cpolymer
 def add_bond(self, **bond):
     """
     Adding bond interaction information:
     Sim = LSimu()
     Sim.add_bond(typeb="harmonic",idbond=1,K=60,R0=1.))
     Sim.add_bond(typeb="fene",idbond=2,K=80,R0=R0,epsilon=1.2,sigma=1)
     """
     self.iBond.append(Bond(**bond))
예제 #11
0
 def __init__(self, args_opt):
     super(Simulation, self).__init__()
     self.control = controller(args_opt)
     self.md_info = md_information(self.control)
     self.bond = Bond(self.control, self.md_info)
     self.angle = Angle(self.control)
     self.dihedral = Dihedral(self.control)
     self.nb14 = NON_BOND_14(self.control, self.dihedral,
                             self.md_info.atom_numbers)
     self.nb_info = nb_infomation(self.control, self.md_info.atom_numbers,
                                  self.md_info.box_length)
     self.LJ_info = Lennard_Jones_Information(self.control)
     self.liujian_info = Langevin_Liujian(self.control,
                                          self.md_info.atom_numbers)
     self.pme_method = Particle_Mesh_Ewald(self.control, self.md_info)
     self.box_length = Tensor(
         np.asarray(self.md_info.box_length, np.float32), mstype.float32)
     self.file = None
예제 #12
0
    def test_exchange_authz_code_missing_token(self):
        data = {"context": {"user": {"name": self.name}}, 'iat': self.issued_at_epoch}
        encoded_jwt = jwt.encode(data, 'secret', 'HS256')
        fake_token_dict = {FenceKeys.ACCESS_TOKEN_KEY: self.fake_access_token,
                           FenceKeys.ID_TOKEN: encoded_jwt,
                           FenceKeys.EXPIRES_AT_KEY: self.expires_at_epoch}

        mock_oauth_adapter = OauthAdapter("foo", "bar", "baz", "qux")
        mock_oauth_adapter.exchange_authz_code = MagicMock(return_value=fake_token_dict)
        mock_oauth_adapter.refresh_access_token = MagicMock(return_value=fake_token_dict)
        mock_oauth_adapter.revoke_refresh_token = MagicMock()

        fence_api = self._mock_fence_api(json.dumps({"private_key_id": "asfasdfasdf"}))
        sam_api = self._mock_sam_api(self.user_id, "email")
        bond = Bond(mock_oauth_adapter, fence_api, sam_api,
                         FenceTokenVendingMachine(fence_api, sam_api, mock_oauth_adapter, provider_name),
                         provider_name, "/context/user/name")

        with self.assertRaises(endpoints.BadRequestException):
            bond.exchange_authz_code("irrelevantString", "redirect", UserInfo(str(uuid.uuid4()), "", "", 30))
예제 #13
0
def main():
    categories = [
        Category("Stocks", Stock.factory()),
        Category("Bank deposits", BankDeposit.factory()),
        Category("Precious metals", Metal.factory()),
        Category("Bonds", Bond.factory())
    ]

    root = Tk()
    menu = Menu(root, categories)
    menu.mainloop()
예제 #14
0
    def proposeBond(self, source, destination, bondCategory, bondFacet,
                    sourceDescriptor, destinationDescriptor, oldCodelet):
        from bond import Bond

        bondFacet.buffer = 100.0
        sourceDescriptor.buffer = 100.0
        destinationDescriptor.buffer = 100.0
        bond = Bond(source, destination, bondCategory, bondFacet,
                    sourceDescriptor, destinationDescriptor)
        urgency = bondCategory.bondDegreeOfAssociation()
        self.newCodelet('bond-strength-tester', oldCodelet, urgency, bond)
예제 #15
0
    def process_cross_bonds(self):
        '''
        if cross bonds have been declared:
        1. tag the corresponding bonds within the tree as no-ops
        2. create a ghost-bond connection from exit_atom to start atom
        3. create a drawn duplicate of the cross bond
        4. append 2 and 3 as branch to the exit atom

        this is unfortunately all a little hackish.
        '''
        cross_bonds = self.options['cross_bond']

        for start1, end1 in cross_bonds:
            start = start1 - 1
            end = end1 - 1

            # retrieve the matching bond that's in the parse tree
            for combo in ((start, end), (end, start)):
                if combo in self.seen_bonds:
                    bond = self.bonds[combo]
                    break
            else: # referenced bond doesn't exist
                raise MCFError, "bond %s-%s doesn't exist" % (start1, end1)

            # very special case: the bond _might_ already be the very
            # last one to be rendered - then we just tag it
            if self.exit_bond.descendants and bond is self.exit_bond.descendants[-1]:
                bond.set_cross(last=True)
                continue

            # create a copy of the bond that will be rendered later
            bond_copy = bond.clone()

            # tag original bond as no-op
            bond.set_link()

            # modify bond copy
            bond_copy.set_cross()
            bond_copy.to_phantom = True     # don't render atom again
            bond_copy.descendants = []      # forget copied descendants

            if bond_copy.start_atom is not self.exit_atom: # usual case
                # create a pseudo bond from the exit atom to the start atom
                # pseudo bond will not be drawn, serves only to "move the pen"
                pseudo_bond = Bond(self.options,
                                self.exit_atom,
                                bond_copy.start_atom)

                pseudo_bond.set_link()
                pseudo_bond.to_phantom = True      # don't render the atom, either

                bond_copy.parent = pseudo_bond
                pseudo_bond.descendants.append(bond_copy)

                pseudo_bond.parent = self.exit_bond
                self.exit_bond.descendants.append(pseudo_bond)

            else: # occasionally, the molecule's exit atom may be the starting point
                  # of the elevated bond
                self.exit_bond.descendants.append(bond_copy)
예제 #16
0
async def validate_input(hass: core.HomeAssistant, data):
    """Validate the user input allows us to connect."""
    def authenticate(bond_hub: Bond) -> bool:
        try:
            bond_hub.getDeviceIds()
            return True
        except RequestConnectionError:
            raise CannotConnect
        except JSONDecodeError:
            return False

    bond = Bond(data[CONF_HOST], data[CONF_ACCESS_TOKEN])

    if not await hass.async_add_executor_job(authenticate, bond):
        raise InvalidAuth

    # Return info that you want to store in the config entry.
    return {"title": data[CONF_HOST]}
예제 #17
0
    def __init__(self, obj):
        self.damping = 20
        if self.name == "Lone Pair":
            self.repulsionfactor = 1.25
            self.lengthfactor = 10
        else:
            self.repulsionfactor = 1
            self.lengthfactor = 20
        self.maxdistance = 100
        self.distancefactor = 100
        self.strengthfactor = 100
        self.totalforce = Vector([0, 0, 0])

        ##from bond.py
        self.bond = Bond(self)

        self.molecule = None
        if "doubles" in self:
            self.charge = self.get_charge()
            self.formalCharge = self.get_formal_charge()
예제 #18
0
def setup(hass, config):
    """Your controller/hub specific code."""

    from bond import Bond

    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = config[DOMAIN]

    host = conf[CONF_HOST]
    token = conf[CONF_TOKEN]

    # Setup connection with devices/cloud
    bond = Bond(bondIp=host, bondToken=token)

    hass.data[DOMAIN] = {'bond_hub': bond}

    hass.helpers.discovery.load_platform('light', DOMAIN, {}, config)
    hass.helpers.discovery.load_platform('fan', DOMAIN, {}, config)

    return True
예제 #19
0
        def create_provider(provider_name):
            client_id = config.get(provider_name, 'CLIENT_ID')
            client_secret = config.get(provider_name, 'CLIENT_SECRET')
            open_id_config_url = config.get(provider_name,
                                            'OPEN_ID_CONFIG_URL')
            fence_base_url = config.get(provider_name, 'FENCE_BASE_URL')
            user_name_path_expr = config.get(provider_name,
                                             'USER_NAME_PATH_EXPR')

            sam_base_url = config.get('sam', 'BASE_URL')

            oauth_adapter = OauthAdapter(client_id, client_secret,
                                         open_id_config_url, provider_name)
            fence_api = FenceApi(fence_base_url)
            sam_api = SamApi(sam_base_url)

            fence_tvm = FenceTokenVendingMachine(fence_api, sam_api,
                                                 oauth_adapter, provider_name)
            return BondProvider(
                fence_tvm,
                Bond(oauth_adapter, fence_api, sam_api, fence_tvm,
                     provider_name, user_name_path_expr))
예제 #20
0
 def __readDataFull(self):
     flagAtomsBegan = False
     flagVelocitiesBegan = False
     flagBondsBegan = False
     flagAnglesBegan = False
     flagDihedralsBegan = False
     flagImpropersBegan = False
     flagMassesBegan = False
     flagPotentialBegan = False
     flagPairCoeffsBegan = False
     flagBondCoeffsBegan = False
     flagAngleCoeffsBegan = False
     flagDihedralCoeffsBegan = False
     flagImproperCoeffsBegan = False
     potential = None
     atoms = []
     atomsNumber = 0
     atomTypesNumber = 0
     bonds = []
     bondsNumber = 0
     bondTypesNumber = 0
     angles = []
     anglesNumber = 0
     angleTypesNumber = 0
     dihedrals = []
     dihedralsNumber = 0
     dihedralTypesNumber = 0
     impropers = []
     impropersNumber = 0
     improperTypesNumber = 0
     comment = None
     zRangesLineNumber = None
     xlo = None
     xhi = None
     ylo = None
     yhi = None
     zlo = None
     zhi = None
     inclines = True
     masses = []
     pairCoeffs = []
     bondCoeffs = []
     angleCoeffs = []
     dihedralCoeffs = []
     improperCoeffs = []
     with open(self['fname'], 'r') as f:
         print('ParserLAMMPSData: started reading from file ',
               self['fname'])
         for lineNumber, line in enumerate(f):
             if lineNumber == 0:
                 comment = line
             elif line.endswith(' atoms\n'):
                 atomsNumber = int(line.split()[0])
                 atoms = [None for i in range(atomsNumber)]
             elif line.endswith(' bonds\n'):
                 bondsNumber = int(line.split()[0])
                 bonds = [None for i in range(bondsNumber)]
             elif line.endswith(' angles\n'):
                 anglesNumber = int(line.split()[0])
                 angles = [None for i in range(anglesNumber)]
             elif line.endswith(' dihedrals\n'):
                 dihedralsNumber = int(line.split()[0])
                 dihedrals = [None for i in range(dihedralsNumber)]
             elif line.endswith(' impropers\n'):
                 impropersNumber = int(line.split()[0])
                 impropers = [None for i in range(impropersNumber)]
             elif line.endswith('atom types\n'):
                 atomTypesNumber = int(line.split()[0])
             elif line.endswith('bond types\n'):
                 bondTypesNumber = int(line.split()[0])
             elif line.endswith('angle types\n'):
                 angleTypesNumber = int(line.split()[0])
             elif line.endswith('dihedral types\n'):
                 dihedralTypesNumber = int(line.split()[0])
             elif line.endswith('improper types\n'):
                 improperTypesNumber = int(line.split()[0])
             elif line.endswith('xlo xhi\n'):
                 xlo = float(line.split()[0])
                 xhi = float(line.split()[1])
             elif line.endswith('ylo yhi\n'):
                 ylo = float(line.split()[0])
                 yhi = float(line.split()[1])
             elif line.endswith('zlo zhi\n'):
                 zlo = float(line.split()[0])
                 zhi = float(line.split()[1])
                 zRangesLineNumber = lineNumber
             elif (zRangesLineNumber is not None
                   and  # String with inclines, 
                   lineNumber == zRangesLineNumber):  # it may be absent.
                 if len(line.split()) == 0:
                     continue
                 if line.split()[0] != '0':
                     continue
                 inclines = False
             elif line.startswith('Masses'):
                 flagMassesBegan = True
             elif line.startswith('Pair Coeffs'):
                 flagPotentialBegan = True
                 flagPairCoeffsBegan = True
             elif line.startswith('Bond Coeffs'):
                 flagBondCoeffsBegan = True
             elif line.startswith('Angle Coeffs'):
                 flagAngleCoeffsBegan = True
             elif line.startswith('Dihedral Coeffs'):
                 flagDihedralCoeffsBegan = True
             elif line.startswith('Improper Coeffs'):
                 flagImproperCoeffsBegan = True
             elif line.startswith('Atoms'):
                 flagAtomsBegan = True
             elif line.startswith('Velocities'):
                 flagVelocitiesBegan = True
             elif line.startswith('Bonds'):
                 flagBondsBegan = True
                 flagVelocitiesBegan = True  # this is not good
                 # they really did not begin
             elif line.startswith('Angles'):
                 flagAnglesBegan = True
             elif line.startswith('Dihedrals'):
                 flagDihedralsBegan = True
             elif line.startswith('Impropers'):
                 flagImpropersBegan = True
             elif flagMassesBegan and not flagPotentialBegan:  # Reading masses
                 if len(line.split()) == 0:
                     continue
                 masses.append(float(line.split()[1]))
             elif flagPotentialBegan and not flagAtomsBegan:
                 if len(line.split()) == 0:
                     continue
                 if flagPairCoeffsBegan and not flagBondCoeffsBegan:
                     pairCoeffs.append(
                         [float(line.split()[1]),
                          float(line.split()[2])])
                 elif flagBondCoeffsBegan and not flagAngleCoeffsBegan:
                     bondCoeffs.append(
                         [float(line.split()[1]),
                          float(line.split()[2])])
                 elif flagAngleCoeffsBegan and not flagDihedralCoeffsBegan:
                     angleCoeffs.append(
                         [float(line.split()[1]),
                          float(line.split()[2])])
                 elif flagDihedralCoeffsBegan and not flagImproperCoeffsBegan:
                     dihedralCoeffs.append([
                         float(line.split()[1]),
                         float(line.split()[2]),
                         float(line.split()[3])
                     ])
                 elif flagImproperCoeffsBegan:
                     improperCoeffs.append([
                         float(line.split()[1]),
                         float(line.split()[2]),
                         float(line.split()[3])
                     ])
             elif flagAtomsBegan and not flagVelocitiesBegan:
                 ls = line.split()
                 if len(ls) < 10:
                     continue
                 atomNumber = int(ls[0])
                 moleculeNumber = int(ls[1])
                 atomType = int(ls[2])
                 atomCharge = float(ls[3])
                 atomX = float(ls[4])
                 atomY = float(ls[5])
                 atomZ = float(ls[6])
                 atomFlagOne = int(ls[7])
                 atomFlagTwo = int(ls[8])
                 atomFlagThree = int(ls[9])
                 if len(ls) > 10:
                     if len(ls) == 11:
                         comment = ls[10]
                     else:
                         comment = " ".join(*ls[10:-1:1])
                 else:
                     comment = None
                 atoms[atomNumber - 1] = Atom(
                     lam_id=atomNumber,
                     x=atomX,
                     y=atomY,
                     z=atomZ,
                     molecule=moleculeNumber,
                     ff_type=atomType,
                     ff_charge=atomCharge,
                     v=None,
                     flags=[atomFlagOne, atomFlagTwo, atomFlagThree],
                     comment=comment)
             elif flagVelocitiesBegan and not flagBondsBegan:
                 ls = line.split()
                 if len(ls) < 4:
                     continue
                 atomNumber = int(ls[0])  # Index = number - 1, because
                 # indices start from 0,
                 # while numbers - from 1.
                 atomVx = float(ls[1])
                 atomVy = float(ls[2])
                 atomVz = float(ls[3])
                 # TODO
                 #atoms[atomNumber - 1].setAtomVx(atomVx=atomVx)
                 #atoms[atomNumber - 1].setAtomVy(atomVy=atomVy)
                 #atoms[atomNumber - 1].setAtomVz(atomVz=atomVz)
             elif flagBondsBegan and not flagAnglesBegan:
                 ls = line.split()
                 if len(ls) < 4:
                     continue
                 bondNumber = int(ls[0])
                 bondType = int(ls[1])
                 atomOneNumber = int(ls[2])
                 atomTwoNumber = int(ls[3])
                 atomOne = atoms[atomOneNumber - 1]
                 atomTwo = atoms[atomTwoNumber - 1]
                 # TODO
                 #neighbors = atomOne.getProperty('neighbors')
                 #if neighbors is None:
                 #    neighbors = []
                 #neighbors.append(atomTwo)
                 #atomOne.updateProperty('neighbors', neighbors)
                 #neighbors = atomTwo.getProperty('neighbors')
                 #if neighbors is None:
                 #    neighbors = []
                 #neighbors.append(atomOne)
                 #atomTwo.updateProperty('neighbors', neighbors)
                 bonds[bondNumber - 1] = Bond(lam_id=bondNumber,
                                              ff_type=bondType,
                                              atomOne=atomOne,
                                              atomTwo=atomTwo)
                 # TODO
                 #bonds[bondNumber - 1].setBoxBoundaries([xlo, xhi,
                 #                                        ylo, yhi,
                 #                                        zlo, zhi])
             elif flagAnglesBegan and not flagDihedralsBegan:
                 ls = line.split()
                 if len(ls) < 5:
                     continue
                 angleNumber = int(ls[0])
                 angleType = int(ls[1])
                 atomOneNumber = int(ls[2])
                 atomTwoNumber = int(ls[3])
                 atomThreeNumber = int(ls[4])
                 atomOne = atoms[atomOneNumber - 1]
                 atomTwo = atoms[atomTwoNumber - 1]
                 atomThree = atoms[atomThreeNumber - 1]
                 angles[angleNumber - 1] = Angle(lam_id=angleNumber,
                                                 ff_type=angleType,
                                                 atomOne=atomOne,
                                                 atomTwo=atomTwo,
                                                 atomThree=atomThree)
             elif flagDihedralsBegan and not flagImpropersBegan:
                 ls = line.split()
                 if len(ls) < 6:
                     continue
                 dihedralNumber = int(ls[0])
                 dihedralType = int(ls[1])
                 atomOneNumber = int(ls[2])
                 atomTwoNumber = int(ls[3])
                 atomThreeNumber = int(ls[4])
                 atomFourNumber = int(ls[5])
                 atomOne = atoms[atomOneNumber - 1]
                 atomTwo = atoms[atomTwoNumber - 1]
                 atomThree = atoms[atomThreeNumber - 1]
                 atomFour = atoms[atomFourNumber - 1]
                 dihedrals[dihedralNumber - 1] = Dihedral(
                     lam_id=dihedralNumber,
                     ff_type=dihedralType,
                     atomOne=atomOne,
                     atomTwo=atomTwo,
                     atomThree=atomThree,
                     atomFour=atomFour)
             elif flagImpropersBegan:
                 ls = line.split()
                 if len(ls) < 6:
                     continue
                 improperNumber = int(ls[0])
                 improperType = int(ls[1])
                 atomOneNumber = int(ls[2])
                 atomTwoNumber = int(ls[3])
                 atomThreeNumber = int(ls[4])
                 atomFoutNumber = int(ls[5])
                 atomOne = atoms[atomOneNumber - 1]
                 atomTwo = atoms[atomTwoNumber - 1]
                 atomThree = atoms[atomThreeNumber - 1]
                 atomFour = atoms[atomFourNumber - 1]
                 impropers[improperNumber - 1] = Improper(
                     lam_id=improperNumber,
                     ff_type=improperType,
                     atomOne=atomOne,
                     atomTwo=atomTwo,
                     atomThree=atomThree,
                     atomFour=atomFour)
             else:
                 if len(line.split()) == 0:
                     continue
                 print('This string does not seem to contain data:', line)
     self['parsedComment'] = comment
     self['parsedPotential'] = potential
     self['parsedAtoms'] = atoms
     self['parsedBonds'] = bonds
     self['parsedAngles'] = angles
     self['parsedDihedrals'] = dihedrals
     self['parsedImpropers'] = impropers
     self['parsedAtomTypesNumber'] = atomTypesNumber
     self['parsedBondTypesNumber'] = bondTypesNumber
     self['parsedAngleTypesNumber'] = angleTypesNumber
     self['parsedDihedralTypesNumber'] = dihedralTypesNumber
     self['parsedImproperTypesNumber'] = improperTypesNumber
     self['parsedBoundaries'] = [xlo, xhi, ylo, yhi, zlo, zhi]
     self['parsedMasses'] = masses
     self['parsedInclines'] = inclines
     self['parsedPairCoeffs'] = pairCoeffs
     self['parsedBondCoeffs'] = bondCoeffs
     self['parsedAngleCoeffs'] = angleCoeffs
     self['parsedDihedralCoeffs'] = dihedralCoeffs
     self['parsedImproperCoeffs'] = improperCoeffs
     print('ParserLAMMPSData finished reading')
예제 #21
0
inventory = Inventory()
print('add cookies')
cookies = Good('cookies', 5)
inventory.add(cookies)
pprint(inventory.goods)
print('add more cookies')
cookies2 = Good('cookies', 5)
inventory.add(cookies2)
pprint(inventory.goods)
print('remove 5 cookies')
inventory.remove(cookies)
pprint(inventory.goods)
inventory.add(PullOption(execution_price=5, underlying='intel'))
pprint(inventory.contracts)
bond1 = Bond(0, num_payments=10, value_payments=1, value_maturity=10)
inventory.add(bond1)
inventory.add(Bond(0, num_payments=100, value_payments=-1,
                   value_maturity=-100))
pprint(inventory.contracts)

scenario = {
    ('price', 'cookies'): 1,
    ('price', 'intel'): 7,
    'interestrate': 0.01
}

print('assets')
pprint(inventory.valued_assets(scenario, usgap))

print('liablities')
예제 #22
0
파일: lsimu.py 프로젝트: oeway/cpolymer
    def generate_interactions_o(self,
                                interaction_name,
                                bond="harmonic",
                                SPB=False,
                                radius=10,
                                cutoff=1.15,
                                reducedv_factor=1,
                                khun=1.):

        if bond == "harmonic":
            temp1 = "bond_style      harmonic\n"
            temp2 = "bond_coeff %i %.2f %.2f"
            ene = 350
        if bond == "fene":
            if SPB:
                temp1 = "bond_style hybrid harmonic fene\n"
                temp2 = "bond_coeff %i fene %.2f %.2f %.2f %.2f"
            else:
                temp1 = "bond_style fene\n"

                temp2 = "bond_coeff %i %.2f %.2f %.2f %.2f"
            ene = 30 * 1
        Bond = [temp1]
        if bond == "fene":
            Bond.append("special_bonds fene\n")
        ene_ratio = 1  #.35
        #Bond.append("special_bonds 0.0 1.0 1.0\n")
        if SPB and False:
            #print radius
            Pair = [
                "pair_style  hybrid lj/cut 3.0 gauss/cut  %.2f \n" %
                (2 * radius) + "pair_modify shift yes\n"
            ]
        else:
            Pair = ["pair_style   lj/cut 1.4 \n" + "pair_modify shift yes\n"]
        Angle = ["angle_style cosine/delta\n"]
        Angle = ["angle_style harmonic\n"]
        keyl = range(1, len(self.natom) + 1)
        for t1 in keyl:
            for t2 in keyl:
                if t2 >= t1:
                    if not self.liaison.has_key("%s-%s" % (t1, t2)):
                        print "Warning liaison between {0} and {1} not defined".format(
                            t1, t2)
                    dist, tybe_b = self.liaison["%s-%s" % (t1, t2)]
                    if cutoff is not None:
                        cut = dist * cutoff
                    else:
                        cut = dist * pow(2., 1 / 6.)
                    odist = copy.deepcopy(dist)
                    #dist=1
                    if bond == "fene":
                        Bond.append(
                            temp2 %
                            (tybe_b, ene_ratio * ene /
                             (dist * dist), 1.5 * dist, ene_ratio, dist) +
                            "\n")
                    else:
                        Bond.append(temp2 % (tybe_b, ene, dist) + "\n")
                    dist = odist
                    precise = ""
                    if SPB and False:
                        precise = "lj/cut"
                    reduced = 1
                    if t1 == t2 and t1 == 3:
                        reduced = 1
                    else:
                        reduced = reducedv_factor

                    Pair.append("""pair_coeff	 %s %s %s %.1f %.2f  %.2f\n""" %
                                (t1, t2, precise, ene_ratio, dist * reduced,
                                 cut * reduced))
                    if self.angle_def is not None and self.Angle != []:
                        for t3 in keyl:
                            if t3 >= t2:
                                dist, tybe_b = self.angle_def["%s-%s-%s" %
                                                              (t1, t2, t3)]
                                k = khun / 2. * dist  # dist = 1 if no ribo involved else 0
                                Angle.append("angle_coeff %i %.3f 180.0\n" %
                                             (tybe_b, k))
        if SPB:
            if bond == "fene":
                Bond.append("bond_coeff %i harmonic 0 0 \n" %
                            (self.liaison["spb"][1]))
                spbond = "bond_coeff %i harmonic %.1f %.1f\n" % (
                    self.liaison["spb"][1], 10, microtubule / realsigma)
            else:
                Bond.append("bond_coeff %i  0 0 \n" % (self.liaison["spb"][1]))
                spbond = "bond_coeff %i %.1f %.1f\n" % (
                    self.liaison["spb"][1], 10, microtubule / realsigma)
            n_i = len(diameter) / 2
            for t1 in range(len(diameter)):
                Pair.append("""pair_coeff	 %i %i %s 0. %.2f  %.2f\n""" %
                            (t1 + 1, num_particle["spb"], precise, dist, cut))

            Pair.append(
                """pair_coeff	 %i %i %s 0. %.2f  %.2f\n""" %
                (num_particle["spb"], num_particle["spb"], precise, dist, cut))

        g = open(interaction_name, "w")
        g.write("".join(Bond) + "\n")
        g.write("".join(Pair) + "\n")
        if self.Angle != []:
            g.write("".join(Angle))
예제 #23
0
class BondTestCase(unittest.TestCase):
    def setUp(self):
        super(BondTestCase, self).setUp()
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()

        self.name = "Bob McBob"
        self.issued_at_epoch = 1528896868
        self.expires_at_epoch = 1529081182
        self.fake_access_token = str(uuid.uuid4())
        self.user_id = str(uuid.uuid4())

        data = {"context": {"user": {"name": self.name}}, 'iat': self.issued_at_epoch}
        encoded_jwt = jwt.encode(data, 'secret', 'HS256')
        fake_token_dict = {FenceKeys.ACCESS_TOKEN_KEY: self.fake_access_token,
                           FenceKeys.REFRESH_TOKEN_KEY: str(uuid.uuid4()),
                           FenceKeys.ID_TOKEN: encoded_jwt,
                           FenceKeys.EXPIRES_AT_KEY: self.expires_at_epoch}

        mock_oauth_adapter = OauthAdapter("foo", "bar", "baz", "qux")
        mock_oauth_adapter.exchange_authz_code = MagicMock(return_value=fake_token_dict)
        mock_oauth_adapter.refresh_access_token = MagicMock(return_value=fake_token_dict)
        mock_oauth_adapter.revoke_refresh_token = MagicMock()

        fence_api = self._mock_fence_api(json.dumps({"private_key_id": "asfasdfasdf"}))
        sam_api = self._mock_sam_api(self.user_id, "email")
        self.bond = Bond(mock_oauth_adapter, fence_api, sam_api,
                         FenceTokenVendingMachine(fence_api, sam_api, mock_oauth_adapter, provider_name),
                         provider_name, "/context/user/name")

    def tearDown(self):
        ndb.get_context().clear_cache()  # Ensure data is truly flushed from datastore/memcache
        self.testbed.deactivate()

    def test_exchange_authz_code(self):
        issued_at, username = self.bond.exchange_authz_code("irrelevantString", "redirect", UserInfo(str(uuid.uuid4()), "", "", 30))
        self.assertEqual(self.name, username)
        self.assertEqual(datetime.fromtimestamp(self.issued_at_epoch), issued_at)

    def test_exchange_authz_code_missing_token(self):
        data = {"context": {"user": {"name": self.name}}, 'iat': self.issued_at_epoch}
        encoded_jwt = jwt.encode(data, 'secret', 'HS256')
        fake_token_dict = {FenceKeys.ACCESS_TOKEN_KEY: self.fake_access_token,
                           FenceKeys.ID_TOKEN: encoded_jwt,
                           FenceKeys.EXPIRES_AT_KEY: self.expires_at_epoch}

        mock_oauth_adapter = OauthAdapter("foo", "bar", "baz", "qux")
        mock_oauth_adapter.exchange_authz_code = MagicMock(return_value=fake_token_dict)
        mock_oauth_adapter.refresh_access_token = MagicMock(return_value=fake_token_dict)
        mock_oauth_adapter.revoke_refresh_token = MagicMock()

        fence_api = self._mock_fence_api(json.dumps({"private_key_id": "asfasdfasdf"}))
        sam_api = self._mock_sam_api(self.user_id, "email")
        bond = Bond(mock_oauth_adapter, fence_api, sam_api,
                         FenceTokenVendingMachine(fence_api, sam_api, mock_oauth_adapter, provider_name),
                         provider_name, "/context/user/name")

        with self.assertRaises(endpoints.BadRequestException):
            bond.exchange_authz_code("irrelevantString", "redirect", UserInfo(str(uuid.uuid4()), "", "", 30))

    def test_generate_access_token(self):
        token = str(uuid.uuid4())
        TokenStore.save(user_id=self.user_id,
                        refresh_token_str=token,
                        issued_at=datetime.fromtimestamp(self.issued_at_epoch),
                        username=self.name,
                        provider_name=provider_name)
        access_token, expires_at = self.bond.generate_access_token(UserInfo(str(uuid.uuid4()), "", "", 30))
        self.assertEqual(self.fake_access_token, access_token)
        self.assertEqual(datetime.fromtimestamp(self.expires_at_epoch), expires_at)

    def test_generate_access_token_errors_when_missing_token(self):
        self.assertRaises(Bond.MissingTokenError, self.bond.generate_access_token, UserInfo(str(uuid.uuid4()), "", "", 30))

    def test_revoke_link_exists(self):
        token = str(uuid.uuid4())
        TokenStore.save(self.user_id, token, datetime.now(), self.name, provider_name)
        user_info = UserInfo(str(uuid.uuid4()), "", "", 30)
        self.bond.fence_tvm.get_service_account_key_json(user_info)
        self.assertIsNotNone(self.bond.fence_tvm._fence_service_account_key(self.user_id).get())

        self.bond.unlink_account(user_info)

        self.assertIsNone(self.bond.fence_tvm._fence_service_account_key(self.user_id).get())
        self.assertIsNone(TokenStore.lookup(self.user_id, provider_name))
        self.bond.oauth_adapter.revoke_refresh_token.assert_called_once()
        self.bond.fence_api.delete_credentials_google.assert_called_once()

    def test_revoke_link_does_not_exists(self):
        user_info = UserInfo(str(uuid.uuid4()), "", "", 30)
        self.bond.unlink_account(user_info)

    def test_link_info_exists(self):
        token = str(uuid.uuid4())
        TokenStore.save(user_id=self.user_id,
                        refresh_token_str=token,
                        issued_at=datetime.fromtimestamp(self.issued_at_epoch),
                        username=self.name,
                        provider_name=provider_name)
        link_info = self.bond.get_link_info(UserInfo(str(uuid.uuid4()), "", "", 30))
        self.assertEqual(token, link_info.token)

    def test_link_info_not_exists(self):
        link_info = self.bond.get_link_info(UserInfo(str(uuid.uuid4()), "", "", 30))
        self.assertIsNone(link_info)

    @staticmethod
    def _mock_fence_api(service_account_json):
        fence_api = FenceApi("")
        fence_api.get_credentials_google = MagicMock(return_value=service_account_json)
        fence_api.delete_credentials_google = MagicMock()
        return fence_api

    @staticmethod
    def _mock_sam_api(subject_id, email):
        sam_api = SamApi("")
        sam_api.user_info = MagicMock(return_value={SamKeys.USER_ID_KEY: subject_id, SamKeys.USER_EMAIL_KEY: email})
        return sam_api
예제 #24
0
def group_builder(codelet):
    # update strength value of the group
    group = codelet.arguments[0]
    __showWhichStringObjectIsFrom(group)
    equivalent = group.string.equivalentGroup(group)
    if equivalent:
        logging.info('already exists...activate descriptors & fizzle')
        group.activateDescriptions()
        equivalent.addDescriptions(group.descriptions)
        return
    # check to see if all objects are still there
    for o in group.objectList:
        assert o in workspace.objects
    # check to see if bonds are there of the same direction
    incompatibleBonds = []  # incompatible bond list
    if len(group.objectList) > 1:
        previous = group.objectList[0]
        for objekt in group.objectList[1:]:
            leftBond = objekt.leftBond
            if leftBond:
                if leftBond.leftObject == previous:
                    continue
                if leftBond.directionCategory == group.directionCategory:
                    continue
                incompatibleBonds += [leftBond]
            previous = objekt
        next_object = group.objectList[-1]
        for objekt in reversed(group.objectList[:-1]):
            rightBond = objekt.rightBond
            if rightBond:
                if rightBond.rightObject == next_object:
                    continue
                if rightBond.directionCategory == group.directionCategory:
                    continue
                incompatibleBonds += [rightBond]
            next_object = objekt
    # if incompatible bonds exist - fight
    group.updateStrength()
    assert __fightIncompatibles(incompatibleBonds, group, 'bonds', 1.0, 1.0)
    # fight incompatible groups
    # fight all groups containing these objects
    incompatibleGroups = group.getIncompatibleGroups()
    assert __fightIncompatibles(incompatibleGroups, group, 'Groups', 1.0, 1.0)
    for incompatible in incompatibleBonds:
        incompatible.break_the_structure()
    # create new bonds
    group.bondList = []
    for i in range(1, len(group.objectList)):
        object1 = group.objectList[i - 1]
        object2 = group.objectList[i]
        if not object1.rightBond:
            if group.directionCategory == slipnet.right:
                source = object1
                destination = object2
            else:
                source = object2
                destination = object1
            category = group.groupCategory.getRelatedNode(slipnet.bondCategory)
            facet = group.facet
            newBond = Bond(source, destination, category, facet,
                           source.getDescriptor(facet),
                           destination.getDescriptor(facet))
            newBond.buildBond()
        group.bondList += [object1.rightBond]
    for incompatible in incompatibleGroups:
        incompatible.break_the_structure()
    group.buildGroup()
    group.activateDescriptions()
    logging.info('building group')
예제 #25
0
class Simulation(nn.Cell):
    """class simulation"""
    def __init__(self, args_opt):
        super(Simulation, self).__init__()
        self.control = controller(args_opt)
        self.md_info = md_information(self.control)
        self.bond = Bond(self.control, self.md_info)
        self.angle = Angle(self.control)
        self.dihedral = Dihedral(self.control)
        self.nb14 = NON_BOND_14(self.control, self.dihedral,
                                self.md_info.atom_numbers)
        self.nb_info = nb_infomation(self.control, self.md_info.atom_numbers,
                                     self.md_info.box_length)
        self.LJ_info = Lennard_Jones_Information(self.control)
        self.liujian_info = Langevin_Liujian(self.control,
                                             self.md_info.atom_numbers)
        self.pme_method = Particle_Mesh_Ewald(self.control, self.md_info)
        self.box_length = Tensor(
            np.asarray(self.md_info.box_length, np.float32), mstype.float32)
        self.file = None

    def Main_Before_Calculate_Force(self):
        """Main Before Calculate Force"""
        _ = self.md_info.MD_Information_Crd_To_Uint_Crd()
        self.md_info.uint_crd_with_LJ = (self.md_info.uint_crd,
                                         self.LJ_info.atom_LJ_type,
                                         self.md_info.charge)
        return self.md_info.uint_crd, self.md_info.uint_crd_with_LJ

    def Initial_Neighbor_List_Update(self, not_first_time):
        """Initial Neighbor List Update"""
        res = self.nb_info.NeighborListUpdate(self.md_info.crd,
                                              self.md_info.crd_old,
                                              self.md_info.uint_crd,
                                              self.md_info.crd_to_uint_crd_cof,
                                              self.md_info.uint_dr_to_dr_cof,
                                              self.box_length, not_first_time)

        return res

    def Main_Calculate_Force(self):
        """main calculate force"""
        self.bond.atom_numbers = self.md_info.atom_numbers
        md_info = self.md_info
        LJ_info = self.LJ_info
        nb_info = self.nb_info
        pme_method = self.pme_method
        bond_frc, _ = self.bond.Bond_Force_With_Atom_Energy(
            md_info.uint_crd, md_info.uint_dr_to_dr_cof)
        frc_t = bond_frc.asnumpy()

        angle_frc, _ = self.angle.Angle_Force_With_Atom_Energy(
            md_info.uint_crd, md_info.uint_dr_to_dr_cof)
        frc_t += angle_frc.asnumpy()

        dihedral_frc, _ = self.dihedral.Dihedral_Force_With_Atom_Energy(
            md_info.uint_crd, md_info.uint_dr_to_dr_cof)
        frc_t += dihedral_frc.asnumpy()

        nb14_frc, _ = self.nb14.Non_Bond_14_LJ_CF_Force_With_Atom_Energy(
            md_info.uint_crd_with_LJ, md_info.uint_dr_to_dr_cof, LJ_info.LJ_A,
            LJ_info.LJ_B)
        frc_t += nb14_frc.asnumpy()

        lj_frc = LJ_info.LJ_Force_With_PME_Direct_Force(
            md_info.atom_numbers, md_info.uint_crd_with_LJ,
            md_info.uint_dr_to_dr_cof, nb_info.nl_atom_numbers,
            nb_info.nl_atom_serial, nb_info.cutoff, pme_method.beta)
        frc_t += lj_frc.asnumpy()

        pme_excluded_frc = pme_method.PME_Excluded_Force(
            md_info.uint_crd, md_info.uint_dr_to_dr_cof, md_info.charge,
            nb_info.excluded_list_start, nb_info.excluded_list,
            nb_info.excluded_numbers)
        frc_t += pme_excluded_frc.asnumpy()

        pme_reciprocal_frc = pme_method.PME_Reciprocal_Force(
            md_info.uint_crd, md_info.charge)
        frc_t += pme_reciprocal_frc.asnumpy()

        self.md_info.frc = Tensor(frc_t, mstype.float32)

        return self.md_info.frc

    def Main_Calculate_Energy(self):
        """main calculate energy"""
        _ = self.bond.Bond_Energy(self.md_info.uint_crd,
                                  self.md_info.uint_dr_to_dr_cof)
        _ = self.angle.Angle_Energy(self.md_info.uint_crd,
                                    self.md_info.uint_dr_to_dr_cof)
        _ = self.dihedral.Dihedral_Engergy(self.md_info.uint_crd,
                                           self.md_info.uint_dr_to_dr_cof)
        _ = self.nb14.Non_Bond_14_LJ_CF_Energy(self.md_info.uint_crd_with_LJ,
                                               self.md_info.uint_dr_to_dr_cof,
                                               self.LJ_info.LJ_A,
                                               self.LJ_info.LJ_B)

        _ = self.LJ_info.LJ_Energy(self.md_info.uint_crd_with_LJ,
                                   self.md_info.uint_dr_to_dr_cof,
                                   self.nb_info.nl_atom_numbers,
                                   self.nb_info.nl_atom_serial,
                                   self.nb_info.cutoff_square)
        _ = self.pme_method.PME_Energy(
            self.md_info.uint_crd, self.md_info.charge,
            self.nb_info.nl_atom_numbers, self.nb_info.nl_atom_serial,
            self.md_info.uint_dr_to_dr_cof, self.nb_info.excluded_list_start,
            self.nb_info.excluded_list, self.nb_info.excluded_numbers)
        _ = self.pme_method.Energy_Device_To_Host()

    def Main_After_Calculate_Energy(self):
        """main after calculate energy"""
        md_info = self.md_info
        LJ_info = self.LJ_info
        bond = self.bond
        angle = self.angle
        dihedral = self.dihedral
        nb14 = self.nb14
        pme_method = self.pme_method

        md_info.total_potential_energy = 0
        md_info.total_potential_energy += bond.sigma_of_bond_ene
        md_info.total_potential_energy += angle.sigma_of_angle_ene
        md_info.total_potential_energy += dihedral.sigma_of_dihedral_ene
        md_info.total_potential_energy += nb14.nb14_lj_energy_sum + nb14.nb14_cf_energy_sum
        md_info.total_potential_energy += LJ_info.LJ_energy_sum
        pme_method.Energy_Device_To_Host()
        md_info.total_potential_energy += pme_method.ee_ene
        print("md_info.total_potential_energy", md_info.total_potential_energy)

    def Main_Iteration_2(self):
        """main iteration2"""
        md_info = self.md_info
        control = self.control
        liujian_info = self.liujian_info

        if md_info.mode > 0 and int(control.Command_Set["thermostat"]) == 1:
            md_info.vel, md_info.crd, md_info.frc, md_info.acc = liujian_info.MD_Iteration_Leap_Frog(
                md_info.d_mass_inverse, md_info.vel, md_info.crd, md_info.frc)

    def Main_After_Iteration(self):
        """main after iteration"""
        md_info = self.md_info
        nb_info = self.nb_info
        md_info.Centerize()
        _ = nb_info.NeighborListUpdate(md_info.crd,
                                       md_info.crd_old,
                                       md_info.uint_crd,
                                       md_info.crd_to_uint_crd_cof,
                                       md_info.uint_dr_to_dr_cof,
                                       self.box_length,
                                       not_first_time=1)

    def Main_Print(self):
        """compute the temperature"""
        md_info = self.md_info
        temperature = md_info.MD_Information_Temperature()
        md_info.h_temperature = temperature
        steps = md_info.steps
        temperature = temperature.asnumpy()
        total_potential_energy = md_info.total_potential_energy.asnumpy()
        sigma_of_bond_ene = self.bond.sigma_of_bond_ene.asnumpy()
        sigma_of_angle_ene = self.angle.sigma_of_angle_ene.asnumpy()
        sigma_of_dihedral_ene = self.dihedral.sigma_of_dihedral_ene.asnumpy()
        nb14_lj_energy_sum = self.nb14.nb14_lj_energy_sum.asnumpy()
        nb14_cf_energy_sum = self.nb14.nb14_cf_energy_sum.asnumpy()
        LJ_energy_sum = self.LJ_info.LJ_energy_sum.asnumpy()
        ee_ene = self.pme_method.ee_ene.asnumpy()
        print(
            "_steps_ _TEMP_ _TOT_POT_ENE_ _BOND_ENE_ "
            "_ANGLE_ENE_ _DIHEDRAL_ENE_ _14LJ_ENE_ _14CF_ENE_ _LJ_ENE_ _CF_PME_ENE_"
        )
        print("{:>7.0f} {:>7.3f} {:>11.3f}".format(
            steps, float(temperature), float(total_potential_energy)),
              end=" ")
        if self.bond.bond_numbers > 0:
            print("{:>10.3f}".format(float(sigma_of_bond_ene)), end=" ")
        if self.angle.angle_numbers > 0:
            print("{:>11.3f}".format(float(sigma_of_angle_ene)), end=" ")
        if self.dihedral.dihedral_numbers > 0:
            print("{:>14.3f}".format(float(sigma_of_dihedral_ene)), end=" ")
        if self.nb14.nb14_numbers > 0:
            print("{:>10.3f} {:>10.3f}".format(float(nb14_lj_energy_sum),
                                               float(nb14_cf_energy_sum)),
                  end=" ")

        print("{:>7.3f}".format(float(LJ_energy_sum)), end=" ")
        print("{:>12.3f}".format(float(ee_ene)))

        if self.file is not None:
            self.file.write(
                "{:>7.0f} {:>7.3f} {:>11.3f} {:>10.3f} {:>11.3f} {:>14.3f} {:>10.3f} {:>10.3f} {:>7.3f}"
                " {:>12.3f}\n".format(steps, float(temperature),
                                      float(total_potential_energy),
                                      float(sigma_of_bond_ene),
                                      float(sigma_of_angle_ene),
                                      float(sigma_of_dihedral_ene),
                                      float(nb14_lj_energy_sum),
                                      float(nb14_cf_energy_sum),
                                      float(LJ_energy_sum), float(ee_ene)))

        return temperature

    def Main_Initial(self):
        """main initial"""
        if self.control.mdout:
            self.file = open(self.control.mdout, 'w')
            self.file.write(
                "_steps_ _TEMP_ _TOT_POT_ENE_ _BOND_ENE_ "
                "_ANGLE_ENE_ _DIHEDRAL_ENE_ _14LJ_ENE_ _14CF_ENE_ _LJ_ENE_ _CF_PME_ENE_\n"
            )

    def Main_Destroy(self):
        """main destroy"""
        if self.file is not None:
            self.file.close()
            print("Save successfully!")
예제 #26
0
def test_atom_sharing():
    b1 = Bond(0, 1)
    b2 = Bond(1, 0)
    b3 = Bond(2, 1)
    b4 = Bond(3, 2)
    assert b1.get_bond_order() == 1

    assert b1.shares_atom(b2) == -1  # they are equal

    # sharing a single atom
    assert b2.shares_atom(b3) == b3.shares_atom(b1)
    assert b3.shares_atom(b2) == b2.shares_atom(b3)

    # no sharing of atoms
    assert b4.shares_atom(b1) == -1
예제 #27
0
 def testWrongGetOtherAtom(self):
     bond = Bond(bondTests.a1, bondTests.a2, None, None)
     self.assertNotEqual(bond.get_other_atom(bondTests.a1), bondTests.a1)
예제 #28
0
파일: lsimu.py 프로젝트: oeway/cpolymer
    def generate_interactions_o(self,interaction_name,bond="harmonic",SPB=False,radius=10,cutoff=1.15,reducedv_factor=1,khun=1.):

        if bond == "harmonic" :
            temp1 = "bond_style      harmonic\n"
            temp2 = "bond_coeff %i %.2f %.2f"
            ene = 350
        if bond == "fene":
            if SPB:
                temp1 = "bond_style hybrid harmonic fene\n"
                temp2 = "bond_coeff %i fene %.2f %.2f %.2f %.2f"
            else:
                temp1 = "bond_style fene\n"
            
                temp2 = "bond_coeff %i %.2f %.2f %.2f %.2f"
            ene = 30 * 1
        Bond = [temp1]
        if bond == "fene":
            Bond.append("special_bonds fene\n")
        ene_ratio=1#.35
        #Bond.append("special_bonds 0.0 1.0 1.0\n")
        if SPB and False:
            #print radius
            Pair = ["pair_style  hybrid lj/cut 3.0 gauss/cut  %.2f \n"%(2*radius) + "pair_modify shift yes\n"]
        else:
            Pair = ["pair_style   lj/cut 1.4 \n" + "pair_modify shift yes\n"]
        Angle = ["angle_style cosine/delta\n"] 
        Angle = ["angle_style harmonic\n"]
        keyl = range(1,len(self.natom)+1)
        for t1 in keyl:
            for t2 in keyl:
                if t2 >= t1:
                    if not self.liaison.has_key("%s-%s"%(t1,t2)):
                        print "Warning liaison between {0} and {1} not defined".format(t1,t2)
                    dist,tybe_b = self.liaison["%s-%s"%(t1,t2)]
                    if  cutoff is not None:                   
                        cut = dist*cutoff
                    else:
                        cut = dist*pow(2.,1/6.) 
                    odist = copy.deepcopy(dist)
                    #dist=1
                    if bond == "fene":
                        Bond.append(temp2 % (tybe_b,ene_ratio * ene/(dist*dist),1.5*dist,ene_ratio,dist) +"\n")
                    else:
                        Bond.append(temp2 % (tybe_b, ene,dist) +"\n")
                    dist = odist
                    precise =""
                    if SPB and False:
                        precise = "lj/cut" 
                    reduced = 1
                    if t1 == t2 and t1 == 3:
                        reduced = 1
                    else:
                        reduced = reducedv_factor 
                        
            
                    Pair.append("""pair_coeff	 %s %s %s %.1f %.2f  %.2f\n"""%(t1,t2,precise,ene_ratio,dist*reduced,cut*reduced))
                    if self.angle_def is not None and self.Angle != []:
                        for t3 in keyl:
                            if t3 >= t2:
                                dist,tybe_b = self.angle_def["%s-%s-%s"%(t1,t2,t3)]
                                k=khun/2. * dist # dist = 1 if no ribo involved else 0
                                Angle.append("angle_coeff %i %.3f 180.0\n"%(tybe_b,k))
        if SPB:
            if bond == "fene":
                Bond.append("bond_coeff %i harmonic 0 0 \n"%(self.liaison["spb"][1]))
                spbond = "bond_coeff %i harmonic %.1f %.1f\n"%(self.liaison["spb"][1],10,microtubule/realsigma)
            else:
                Bond.append("bond_coeff %i  0 0 \n"%(self.liaison["spb"][1]))
                spbond = "bond_coeff %i %.1f %.1f\n"%(self.liaison["spb"][1],10,microtubule/realsigma)
            n_i = len(diameter)/2
            for t1 in range(len(diameter) ):
                Pair.append("""pair_coeff	 %i %i %s 0. %.2f  %.2f\n"""%(t1+1,num_particle["spb"],precise,dist,cut))
              
            Pair.append("""pair_coeff	 %i %i %s 0. %.2f  %.2f\n"""%(num_particle["spb"],num_particle["spb"],precise,dist,cut))
        
        g = open(interaction_name,"w")
        g.write("".join(Bond)+"\n")
        g.write("".join(Pair)+"\n")
        if self.Angle != []:
            g.write("".join(Angle))
예제 #29
0
from bond import (Bond,Directions)
import time
from pprint import pprint

bond = Bond(bondIp='', bondToken='')

device = bond.getDevice('')
예제 #30
0
def test_type_checking():
    b = Bond(2, 0)
    with pytest.raises(TypeError):
        value_long = float(
            2)  # do not test long because it obsolete in python3
        b.get_nbr_atom_idx(value_long)
예제 #31
0
localtime = datetime.datetime(2012,9,19)

# Import our Treasury data
f = io.open('treasuries.csv', 'r')
data = f.read()
bonds = []
i = 0
for line in data.split('\n'):
    # import pdb; pdb.set_trace()
    i += 1
    if (i == 1): continue
    entries = line.split(',')
    
    # if (len(entries) != 9): continue
    b = Bond()
    b.freq = 2
    b.cusip = entries[0]
    b.desc = entries[1]
    b.couponRate = float(entries[2]) / 100.0
    b.maturity = datetime.datetime.strptime(entries[3], '%d-%b-%y')
    b.bid = float(entries[4]) / 100
    b.ask = float(entries[5]) / 100
    bonds.append(b)
f.close()

tr = [] # times to maturity
yr = [] # yields

for b in bonds:
    print b.maturity
예제 #32
0
 def testNotContainsAtom(self):
     bond = Bond(bondTests.a1, bondTests.a2, None, None)
     self.assertFalse(bond.contains_atom(bondTests.a3))