create the polymer from the monomer

        Args:
            monomer (Molecule)
            mon_vector (numpy.array): molecule vector that starts from the
                start atom index to the end atom index
351809
def _create(self, monomer, mon_vector):
        
        while self.length != (self.n_units-1):
            if self.linear_chain:
                move_direction = np.array(mon_vector) / np.linalg.norm(mon_vector)
            else:
                move_direction = self._next_move_direction()
            self._add_monomer(monomer.copy(), mon_vector, move_direction)
1216595
public static Monomer getMonomer(Element monomer) throws MonomerException {
    Monomer m = new Monomer();
    Namespace ns = monomer.getNamespace();
    m.setAlternateId(monomer.getChildText(MONOMER_ID_ELEMENT, ns));
    m.setCanSMILES(monomer.getChildText(MONOMER_SMILES_ELEMENT, ns));
    String encodedMolfile = monomer.getChildText(MONOMER_MOL_FILE_ELEMENT, ns);

    String molfile = null;
    try {
      molfile = MolfileEncoder.decode(encodedMolfile);
    } catch (EncoderException ex) {
      throw new MonomerException("Invalid monomer molfile");
    }
    m.setMolfile(molfile);
    m.setMonomerType(monomer.getChildText(MONOMER_TYPE_ELEMENT, ns));
    m.setPolymerType(monomer.getChildText(POLYMER_TYPE_ELEMENT, ns));
    m.setNaturalAnalog(monomer.getChildText(NATURAL_ANALOG_ELEMENT, ns));
    m.setName(monomer.getChildText(MONOMER_NAME_ELEMENT, ns));
    Element attachmentElement = monomer.getChild(ATTACHEMENTS_ELEMENT, ns);

    if (null != attachmentElement) {
      List attachments = attachmentElement.getChildren(ATTACHEMENT_ELEMENT, ns);
      List<Attachment> l = new ArrayList<Attachment>();
      Iterator i = attachments.iterator();
      while (i.hasNext()) {
        Element attachment = (Element) i.next();
        Attachment att = getAttachment(attachment);
        l.add(att);
      }
      m.setAttachmentList(l);
    }
    return m;
  }
1150295
public boolean isSameType(Monomer m) {
    String analog1 = getNaturalAnalog();
    if (null == analog1) {
      analog1 = getAlternateId();
    }
    String analog2 = m.getNaturalAnalog();
    if (null == analog2) {
      analog2 = m.getAlternateId();
    }
    if (getMonomerType().equals(m.getMonomerType())
        && getPolymerType().equals(m.getPolymerType())
        && analog1.equals(analog2)) {
      return true;
    } else {
      return false;
    }
  }
595966
public List<Monomer> getAllMonomersList() {
    List<Monomer> monomers = new ArrayList<Monomer>();
    for (String polymerType : getPolymerTypeSet()) {
      Map<String, Monomer> map = getMonomers(polymerType);
      monomers.addAll(map.values());
    }
    return monomers;

  }
793706
def read_molden(inputfile, start_index=0, get_bonds=True):
    
    from chemcoord.cartesian_coordinates.cartesian_class_main import Cartesian
    with open(inputfile, 'r') as f:
        found = False
        while not found:
            line = f.readline()
            if '[N_GEO]' in line:
                found = True
                number_of_molecules = int(f.readline().strip())

        energies = []
        found = False
        while not found:
            line = f.readline()
            if 'energy' in line:
                found = True
                for _ in range(number_of_molecules):
                    energies.append(float(f.readline().strip()))

        found = False
        while not found:
            line = f.readline()
            if '[GEOMETRIES] (XYZ)' in line:
                found = True
                current_line = f.tell()
                number_of_atoms = int(f.readline().strip())
                f.seek(current_line)

        cartesians = []
        for energy in energies:
            cartesian = Cartesian.read_xyz(
                f, start_index=start_index, get_bonds=get_bonds,
                nrows=number_of_atoms, engine='python')
            cartesian.metadata['energy'] = energy
            cartesians.append(cartesian)
    return cartesians
311102
def set_base_initial_condition(model, monomer, value):
    """"""
    # Build up monomer pattern dict
    sites_dict = {}
    for site in monomer.sites:
        if site in monomer.site_states:
            if site == 'loc' and 'cytoplasm' in monomer.site_states['loc']:
                sites_dict['loc'] = 'cytoplasm'
            else:
                sites_dict[site] = monomer.site_states[site][0]
        else:
            sites_dict[site] = None
    mp = monomer(**sites_dict)
    pname = monomer.name + '_0'
    try:
        p = model.parameters[pname]
        p.value = value
    except KeyError:
        p = Parameter(pname, value)
        model.add_component(p)
        model.initial(mp, p)
125924
def assign_rotatable(mol):
    """"""
    mol.require("Valence")
    mol.require("Topology")
    bs = set([(u, v) for u, v, _ in mol.bonds_iter()])
    for r in mol.rings:
        for a, b in iterator.consecutive(r + [r[0]], 2):
            bs -= {(a, b)}
            bs -= {(b, a)}
    for u, v in bs:
        unc = mol.neighbor_count(u)
        vnc = mol.neighbor_count(v)
        bc = mol.bond(u, v).order
        if bc == 1 and (unc > 1 and vnc > 1):
            mol.bond(u, v).rotatable = True
    mol.descriptors.add("Rotatable")
730540
public String saveMonomerToStore(Monomer monomer) {
    String res = "";
    CloseableHttpResponse response = null;

    try {
      response = WSAdapterUtils.putResource(monomer.toJSON(),
          MonomerStoreConfiguration.getInstance()
              .getWebserviceNucleotidesPutFullURL());
      LOG.debug(response.getStatusLine().toString());

      JsonFactory jsonf = new JsonFactory();
      InputStream instream = response.getEntity().getContent();

      JsonParser jsonParser = jsonf.createParser(instream);

      while (!jsonParser.isClosed()) {
        JsonToken jsonToken = jsonParser.nextToken();
        if (JsonToken.FIELD_NAME.equals(jsonToken)) {
          String fieldName = jsonParser.getCurrentName();
          LOG.debug("Field name: " + fieldName);
          jsonParser.nextToken();
          if (fieldName.equals("monomerShortName")) {
            res = jsonParser.getValueAsString();
            break;
          }
        }
      }

      EntityUtils.consume(response.getEntity());

    } catch (Exception e) {
      LOG.error("Saving monomer failed!", e);
      return "";
    } finally {
      try {
        if (response != null) {
          response.close();
        }
      } catch (IOException e) {
        LOG.debug("Closing resources failed.", e);
        return res;
      }
    }

    return res;
  }
1206013
def _Struct_set_Poly(Poly, pos=None, extent=None, arrayorder='C',
                     Type='Tor', Clock=False):
    

    # Make Poly closed, counter-clockwise, with '(cc,N)' layout and arrayorder
    Poly = _GG.Poly_Order(Poly, order='C', Clock=False,
                          close=True, layout='(cc,N)', Test=True)
    assert Poly.shape[0]==2, "Arg Poly must be a 2D polygon !"
    fPfmt = np.ascontiguousarray if arrayorder=='C' else np.asfortranarray

    # Get all remarkable points and moments
    NP = Poly.shape[1]-1
    P1Max = Poly[:,np.argmax(Poly[0,:])]
    P1Min = Poly[:,np.argmin(Poly[0,:])]
    P2Max = Poly[:,np.argmax(Poly[1,:])]
    P2Min = Poly[:,np.argmin(Poly[1,:])]
    BaryP = np.sum(Poly[:,:-1],axis=1,keepdims=False)/(Poly.shape[1]-1)
    BaryL = np.array([(P1Max[0]+P1Min[0])/2., (P2Max[1]+P2Min[1])/2.])
    TorP = plg.Polygon(Poly.T)
    Surf = TorP.area()
    BaryS = np.array(TorP.center()).flatten()

    # Get lim-related indicators
    noccur = int(pos.size)
    Multi = noccur>1

    # Get Tor-related quantities
    if Type.lower()=='lin':
        Vol, BaryV = None, None
    else:
        Vol, BaryV = _GG.Poly_VolAngTor(Poly)
        msg = "Pb. with volume computation for Ves object of type 'Tor' !"
        assert Vol>0., msg

    # Compute the non-normalized vector of each side of the Poly
    Vect = np.diff(Poly,n=1,axis=1)
    Vect = fPfmt(Vect)

    # Compute the normalised vectors directed inwards
    Vin = np.array([Vect[1,:],-Vect[0,:]])
    if not _GG.Poly_isClockwise(Poly):
        Vin = -Vin
    Vin = Vin/np.hypot(Vin[0,:],Vin[1,:])[np.newaxis,:]
    Vin = fPfmt(Vin)

    poly = _GG.Poly_Order(Poly, order=arrayorder, Clock=Clock,
                          close=False, layout='(cc,N)', Test=True)

    # Get bounding circle
    circC = BaryS
    r = np.sqrt(np.sum((poly-circC[:,np.newaxis])**2,axis=0))
    circr = np.max(r)

    dout = {'Poly':poly, 'pos':pos, 'extent':extent,
            'noccur':noccur, 'Multi':Multi, 'nP':NP,
            'P1Max':P1Max, 'P1Min':P1Min, 'P2Max':P2Max, 'P2Min':P2Min,
            'BaryP':BaryP, 'BaryL':BaryL, 'BaryS':BaryS, 'BaryV':BaryV,
            'Surf':Surf, 'VolAng':Vol, 'Vect':Vect, 'VIn':Vin,
            'circ-C':circC, 'circ-r':circr, 'Clock':Clock}
    return dout
385155
public Monomer getMonomer(String polymerType, String alternateId) {
	Map<String, Monomer> map1 = monomerDB.get(polymerType);
	//alternateId = alternateId.toUpperCase();
    return monomerDB.get(polymerType).get(alternateId);
  }
288650
public Monomer getSugarMonomer(MonomerStore monomerStore) {
    String sugarSymbol = getSugarSymbol();
    if (sugarSymbol != null && !sugarSymbol.equalsIgnoreCase("")) {
      try {
        Map<String, Monomer> monomers = monomerStore.getMonomers(Monomer.NUCLIEC_ACID_POLYMER_TYPE);
        Monomer m = monomers.get(sugarSymbol);
        return m;
      } catch (Exception ex) {
        LOG.info("Unable to get sugar monomer for "
            + sugarSymbol);
        return null;
      }
    } else {
      return null;
    }
  }
862174
def initialize(
            self, M_c, M_r, T, seed, initialization=b'from_the_prior',
            row_initialization=-1, n_chains=1,
            ROW_CRP_ALPHA_GRID=(), COLUMN_CRP_ALPHA_GRID=(),
            S_GRID=(), MU_GRID=(), N_GRID=31,):
        
        # FIXME: why is M_r passed?
        arg_tuples = self.get_initialize_arg_tuples(
            M_c, M_r, T, initialization, row_initialization, n_chains,
            ROW_CRP_ALPHA_GRID, COLUMN_CRP_ALPHA_GRID, S_GRID, MU_GRID, N_GRID,
            make_get_next_seed(seed),)

        chain_tuples = self.mapper(self.do_initialize, arg_tuples)
        X_L_list, X_D_list = zip(*chain_tuples)
        if n_chains == 1:
            X_L_list, X_D_list = X_L_list[0], X_D_list[0]

        return X_L_list, X_D_list
930890
def __create_vector(self, *vec) -> Vector3:
        
        import numbers

        if len(vec) == 1:
            if hasattr(vec[0], "__getitem__"):  # Support all subscriptable types.
                try:
                    x = float(vec[0][0])
                    y = float(vec[0][1])
                    try:
                        z = float(vec[0][2])
                    except (ValueError, IndexError):
                        z = 0
                except ValueError:
                    raise ValueError(f"Unexpected type(s) for creating vector: {type(vec[0][0])}, {type(vec[0][1])}")
                except IndexError:
                    raise IndexError(f"Unexpected IndexError when creating vector from type: {type(vec[0])}")
            elif isinstance(vec[0], Vector3.Vector3):
                x = vec[0].X()
                y = vec[0].Y()
                z = vec[0].Z()
            elif isinstance(vec[0], GameDataStructVector3):
                x = vec[0].x
                y = vec[0].y
                z = vec[0].z
            else:
                raise ValueError(f"Unexpected type for creating vector: {type(vec[0])}")
        elif len(vec) == 2 or len(vec) == 3:
            if isinstance(vec[0], numbers.Number) and isinstance(vec[1], numbers.Number):
                x = vec[0]
                y = vec[1]
                if len(vec) == 2:
                    z = 0
                else:
                    if isinstance(vec[2], numbers.Number):
                        z = vec[2]
                    else:
                        raise ValueError(f"Unexpected type for creating vector: {type(vec[0])}")
            else:
                raise ValueError(f"Unexpected type(s) for creating vector: {type(vec[0])}, {type(vec[1])}")
        else:
            raise ValueError("Unexpected number of arguments for creating vector")

        return Vector3.CreateVector3(self.builder, x, y, z)
1115848
def polyder(c, m=1, scl=1, axis=0):
    '''
    '''
    c = list(c)
    cnt = int(m)

    if cnt == 0:
        return c

    n = len(c)
    if cnt >= n:
        c = c[:1]*0
    else:
        for i in range(cnt):
            n = n - 1
            c *= scl
            der = [0.0 for _ in range(n)]
            for j in range(n, 0, -1):
                der[j - 1] = j*c[j]
            c = der
    return c
389838
@SuppressWarnings("unchecked")
  private void createVector() {
    fpVector = new List[vectorSize];
    keyVector = new List[vectorSize];
    ratio = new double[vectorSize];

    for (int i = 0; i < vectorSize; i++) {
      fpVector[i] = Collections.synchronizedList(new ArrayList<Key>());
      keyVector[i] = Collections.synchronizedList(new ArrayList<Key>());
      ratio[i] = 0.0;
    }
  }
632662
public final static void changeMonomerNotation(int position, PolymerNotation polymer, MonomerNotation not) {
		polymer.getPolymerElements().getListOfElements().set(position, not);
	}
73156
def _build(self, lexer):
        
        atom_number = 1
        while True:
            token = next(lexer)
            key = token.__class__.__name__

            if key == 'CtabCountsLine':
                self[key].update(token._asdict())

            elif key == 'CtabAtomBlock':
                self[key].append(Atom(atom_number=str(atom_number), **token._asdict()))
                atom_number += 1

            elif key == 'CtabBondBlock':
                first_atom_number, second_atom_number, bond_type, bond_stereo, \
                not_used1, bond_topology, reacting_center_status = token

                first_atom = self.atoms[int(first_atom_number) - 1]
                second_atom = self.atoms[int(second_atom_number) - 1]
                first_atom.neighbors.append(second_atom)
                second_atom.neighbors.append(first_atom)

                bond = Bond(first_atom=first_atom, second_atom=second_atom, bond_type=bond_type,
                            bond_stereo=bond_stereo, not_used1=not_used1, bond_topology=bond_topology,
                            reacting_center_status=reacting_center_status)
                self[key].append(bond)

            elif key == 'CtabPropertiesBlock':
                property_name = token.name
                keys = self.ctab_conf[self.version][property_name]['values']
                ctab_properties = more_itertools.sliced(token.line.split()[3:], len(keys))

                for ctab_property in ctab_properties:
                    atom_number, property_value = ctab_property
                    self.atoms[int(atom_number) - 1]._ctab_property_data[property_name] = property_value

            elif key == 'CtabBlockEnd':
                break

            else:
                raise KeyError('Ctab object does not supposed to have any other information: "{}".'.format(key))