Update BEL1 pmod() protein modification term
502716
def convert_pmod(pmod):
    """"""

    if pmod.args[0].value in spec["bel1_migration"]["protein_modifications"]:
        pmod.args[0].value = spec["bel1_migration"]["protein_modifications"][
            pmod.args[0].value
        ]

    return pmod
250309
def _assemble_transphosphorylation(self, stmt):
        """"""
        # Check our assumptions about the bound condition of the enzyme
        assert len(stmt.enz.bound_conditions) == 1
        assert stmt.enz.bound_conditions[0].is_bound
        # Create a modified protein node for the bound target
        sub_agent = deepcopy(stmt.enz.bound_conditions[0].agent)
        sub_agent.mods.append(stmt._get_mod_condition())
        self._add_nodes_edges(stmt.enz, sub_agent, pc.DIRECTLY_INCREASES,
                              stmt.evidence)
768724
@Override
	public void toPDB(StringBuffer buf){
		//          1         2         3         4         5         6         7
		//01234567890123456789012345678901234567890123456789012345678901234567890123456789
		//HEADER    COMPLEX (SERINE PROTEASE/INHIBITORS)    06-FEB-98   1A4W
		//TITLE     CRYSTAL STRUCTURES OF THROMBIN WITH THIAZOLE-CONTAINING
		//TITLE    2 INHIBITORS: PROBES OF THE S1' BINDING SITE

		printHeader(buf);
		printTitle(buf);
		printExpdata(buf);
		printAuthors(buf);
		printResolution(buf);

	}
1016147
public static boolean hasNucleotideModification(PolymerNotation polymer) throws NotationException {
		for (MonomerNotation current : polymer.getPolymerElements().getListOfElements()) {
			if (hasModification(current)) {
				return true;
			}
		}
		return false;
	}
241380
private void recordUnidentifiableAtomLinkages(List<ModifiedCompound> modComps,
			List<Group> ligands) {

		// first put identified linkages in a map for fast query
		Set<StructureAtomLinkage> identifiedLinkages = new HashSet<StructureAtomLinkage>();
		for (ModifiedCompound mc : modComps) {
			identifiedLinkages.addAll(mc.getAtomLinkages());
		}

		// record
		// cross link
		int nRes = residues.size();
		for (int i=0; i<nRes-1; i++) {
			Group group1 = residues.get(i);
			for (int j=i+1; j<nRes; j++) {
				Group group2 = residues.get(j);
				List<Atom[]> linkages = StructureUtil.findAtomLinkages(
						group1, group2, true, bondLengthTolerance);
				for (Atom[] atoms : linkages) {
					StructureAtomLinkage link = StructureUtil.getStructureAtomLinkage(atoms[0],
							true, atoms[1], true);
					unidentifiableAtomLinkages.add(link);
				}
			}
		}

		// attachment
		int nLig = ligands.size();
		for (int i=0; i<nRes; i++) {
			Group group1 = residues.get(i);
			for (int j=0; j<nLig; j++) {
				Group group2 = ligands.get(j);
				if (group1.equals(group2)) { // overlap between residues and ligands
					continue;
				}
				List<Atom[]> linkages = StructureUtil.findAtomLinkages(
						group1, group2, false, bondLengthTolerance);
				for (Atom[] atoms : linkages) {
					StructureAtomLinkage link = StructureUtil.getStructureAtomLinkage(atoms[0],
							true, atoms[1], false);
					unidentifiableAtomLinkages.add(link);
				}
			}
		}
	}
749953
def parse_psimitab(content, fmt='tab27'):
    
    columns = [
        'Unique identifier for interactor A',
        'Unique identifier for interactor B',
        'Alternative identifier for interactor A',
        'Alternative identifier for interactor B',
        'Aliases for A',
        'Aliases for B',
        'Interaction detection methods',
        'First author',
        'Identifier of the publication',
        'NCBI Taxonomy identifier for interactor A',
        'NCBI Taxonomy identifier for interactor B',
        'Interaction types',
        'Source databases',
        'Interaction identifier(s)',
        'Confidence score']
    columns += [
        'Complex expansion',
        'Biological role A', 'Biological role B',
        'Experimental role A', 'Experimental role B',
        'Interactor type A', 'Interactor type B',
        'Xref for interactor A', 'Xref for interactor B',
        'Xref for the interaction',
        'Annotaions for interactor A', 'Annotations for interactor B',
        'Annotations for the interaction',
        'NCBI Taxonomy identifier for the host organism',
        'Prameters of the interaction',
        'Creaction date', 'Update date',
        'Checksum for the interactor A', 'Checksum for the interactor B',
        'Checksum for the interaction',
        'negative',
        'Feature(s) for interactor A', 'Feature(s) for interactor B',
        'Stoichiometry for interactor A', 'Stoichiometroy for interactor B',
        'Participant identification method for interactor A',
        'Participant identification method for interactor B'
        ]
    if fmt == 'tab25':
        columns = columns[: 15]

    rexp = re.compile(r"(?P<fields>((\"([^\"]|((?<=\\)\"))*\")|([^\t\"])|((?<=\\)\"))+)(\t|$)")

    retval = []
    for line in content.split('\n'):
        line = line.strip()
        if line == '' or line[0] == '#':
            continue

        start = 0
        tmp = []
        for mobj in rexp.finditer(line):
            if mobj.start() != start:
                print(repr(line))
            assert mobj.start() == start
            start = mobj.end()
            tmp.append(mobj.group('fields'))
        assert len(tmp) == len(columns)
        retval.append(dict(zip(columns, tmp)))
    return retval
916640
def add_ms1_quant_from_top3_mzidtsv(proteins, psms, headerfields, protcol):
    """"""
    if not protcol:
        protcol = mzidtsvdata.HEADER_MASTER_PROT
    top_ms1_psms = generate_top_psms(psms, protcol)
    for protein in proteins:
        prot_acc = protein[prottabledata.HEADER_PROTEIN]
        prec_area = calculate_protein_precursor_quant(top_ms1_psms, prot_acc)
        outprotein = {k: v for k, v in protein.items()}
        outprotein[headerfields['precursorquant'][
            prottabledata.HEADER_AREA][None]] = str(prec_area)
        yield outprotein
1285239
function templateNodeTransformation( $functionName, &$node,
                                         $tpl, &$parameters, $privateData )
    {
        // {while <condition> [sequence <sequence_array> as $<sequence_var>]}

        $tpl->WhileCounter++;
        $newNodes      = array();
        $nodePlacement = eZTemplateNodeTool::extractFunctionNodePlacement( $node );
        $uniqid        =  md5( $nodePlacement[2] ) . "_" . $tpl->WhileCounter;

        $loop = new eZTemplateCompiledLoop( eZTemplateWhileFunction::FUNCTION_NAME,
                                            $newNodes, $parameters, $nodePlacement, $uniqid,
                                            $node, $tpl, $privateData );


        $loop->initVars();

        // loop header
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "while ( 1 ) // while\n{" );
        $newNodes[] = eZTemplateNodeTool::createSpacingIncreaseNode();
        $newNodes[] = eZTemplateNodeTool::createVariableNode( false, $parameters['condition'], $nodePlacement, array( 'treat-value-as-non-object' => true ),
                                                              "while_cond" );
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "if ( ! \$while_cond ) break;\n" );

        $loop->processBody();

        // loop footer
        $newNodes[] = eZTemplateNodeTool::createSpacingDecreaseNode();
        $newNodes[] = eZTemplateNodeTool::createCodePieceNode( "} // end of while\n" );
        $newNodes[] = eZTemplateNodeTool::createVariableUnsetNode( 'while_cond' );
        $loop->cleanup();

        return $newNodes;
    }
682772
def remove_isolated_residues(seq, len = 2)
      gap_starts = seq.to_enum(:scan, /(-\w{1,#{len}}-)/i).map { |_m| $`.size + 1 }
      # remove isolated residues
      gap_starts.each do |i|
        (i..i + len - 1).each { |j| seq[j] = '-' if isalpha(seq[j]) }
      end
      # remove isolated gaps
      res_starts = seq.to_enum(:scan, /([?\w]-{1,2}[?\w])/i).map { |_m| $`.size + 1 }
      res_starts.each do |i|
        (i..i + len - 1).each { |j| seq[j] = '?' if seq[j] == '-' }
      end
      seq
    end
944213
def GetRosettaResidueMap(self, ConvertMSEToAtom = False, RemoveIncompleteFinalResidues = False, RemoveIncompleteResidues = False):
        ''''''
        raise Exception('This code looks to be deprecated. Use construct_pdb_to_rosetta_residue_map instead.')
        chain = None
        sequences = {}
        residue_map = {}
        resid_set = set()
        resid_list = []

        DNA_residues = set([' DA', ' DC', ' DG', ' DT'])
        chains = []
        self.RAW_ATOM_SEQUENCE = []
        essential_atoms_1 = set(['CA', 'C', 'N'])#, 'O'])
        essential_atoms_2 = set(['CA', 'C', 'N'])#, 'OG'])
        current_atoms = set()
        atoms_read = {}
        oldchainID = None
        removed_residue = {}
        for line in self.lines:
            if line[0:4] == 'ATOM' or (ConvertMSEToAtom and (line[0:6] == 'HETATM') and (line[17:20] == 'MSE')):
                chainID = line[21]
                if missing_chain_ids.get(self.pdb_id):
                    chainID = missing_chain_ids[self.pdb_id]
                if chainID not in chains:
                    chains.append(chainID)
                residue_longname = line[17:20]
                if residue_longname in DNA_residues:
                    # Skip DNA
                    continue
                if residue_longname == 'UNK':
                    # Skip unknown residues
                    continue
                if residue_longname not in allowed_PDB_residues_types and not(ConvertMSEToAtom and residue_longname == 'MSE'):
                    if not self.strict:
                        # Skip unknown residues
                        continue
                    else:
                        raise NonCanonicalResidueException("Residue %s encountered: %s" % (line[17:20], line))
                else:
                    resid = line[21:27]
                    #print(chainID, residue_longname, resid)
                    #print(line)
                    #print(resid_list)
                    if resid not in resid_set:
                        removed_residue[chainID] = False
                        add_residue = True
                        if current_atoms:
                            if RemoveIncompleteResidues and essential_atoms_1.intersection(current_atoms) != essential_atoms_1 and essential_atoms_2.intersection(current_atoms) != essential_atoms_2:
                                oldChain = resid_list[-1][0]
                                oldResidueID = resid_list[-1][1:]
                                print("The last residue '%s', %s, in chain %s is missing these atoms: %s." % (resid_list[-1], residue_longname, oldChain, essential_atoms_1.difference(current_atoms) or essential_atoms_2.difference(current_atoms)))
                                resid_set.remove(resid_list[-1])
                                #print("".join(resid_list))
                                resid_list = resid_list[:-1]
                                if oldchainID:
                                    removed_residue[oldchainID] = True
                                #print("".join(resid_list))
                                #print(sequences[oldChain])
                                if sequences.get(oldChain):
                                    sequences[oldChain] = sequences[oldChain][:-1]

                                if residue_map.get(oldChain):
                                    residue_map[oldChain] = residue_map[oldChain][:-1]

                                #print(sequences[oldChain]
                        else:
                            assert(not(resid_set))
                        current_atoms = set()
                        atoms_read[chainID] = set()
                        atoms_read[chainID].add(line[12:15].strip())
                        resid_set.add(resid)
                        resid_list.append(resid)
                        chainID = line[21]

                        sequences[chainID] = sequences.get(chainID, [])
                        if residue_longname in non_canonical_amino_acids:
                            sequences[chainID].append(non_canonical_amino_acids[residue_longname])
                        else:
                            sequences[chainID].append(residue_type_3to1_map[residue_longname])

                        residue_map[chainID] = residue_map.get(chainID, [])
                        if residue_longname in non_canonical_amino_acids:
                            residue_map[chainID].append((resid, non_canonical_amino_acids[residue_longname]))
                        else:
                            residue_map[chainID].append((resid, residue_type_3to1_map[residue_longname]))

                        oldchainID = chainID
                    else:
                        #atoms_read[chainID] = atoms_read.get(chainID, set())
                        atoms_read[chainID].add(line[12:15].strip())
                    current_atoms.add(line[12:15].strip())
        if RemoveIncompleteFinalResidues:
            # These are (probably) necessary for Rosetta to keep the residue. Rosetta does throw away residues where only the N atom is present if that residue is at the end of a chain.
            for chainID, sequence_list in sequences.iteritems():
                if not(removed_residue[chainID]):
                    if essential_atoms_1.intersection(atoms_read[chainID]) != essential_atoms_1 and essential_atoms_2.intersection(atoms_read[chainID]) != essential_atoms_2:
                        print("The last residue %s of chain %s is missing these atoms: %s." % (sequence_list[-1], chainID, essential_atoms_1.difference(atoms_read[chainID]) or essential_atoms_2.difference(atoms_read[chainID])))
                        oldResidueID = sequence_list[-1][1:]
                        residue_map[chainID] = residue_map[chainID][0:-1]
                        sequences[chainID] = sequence_list[0:-1]


        for chainID, sequence_list in sequences.iteritems():
            sequences[chainID] = "".join(sequence_list)
            assert(sequences[chainID] == "".join([res_details[1] for res_details in residue_map[chainID]]))
        for chainID in chains:
            for a_acid in sequences.get(chainID, ""):
                self.RAW_ATOM_SEQUENCE.append((chainID, a_acid))

        residue_objects = {}
        for chainID in residue_map.keys():
            residue_objects[chainID] = []
        for chainID, residue_list in residue_map.iteritems():
            for res_pair in residue_list:
                resid = res_pair[0]
                resaa = res_pair[1]
                assert(resid[0] == chainID)
                residue_objects[chainID].append((resid[1:].strip(), resaa))

        return sequences, residue_objects
392289
private int getGroupTypIndicator(PolymerType polymerType) {
		if(PolymerType.PROTEIN_ONLY.contains(polymerType)){
			return 1;
		}
		if(PolymerType.POLYNUCLEOTIDE_ONLY.contains(polymerType)){
			return 2;
		}
		return 0;
	}
1197848
public static IBioPolymer addAminoAcidAtNTerminus(IBioPolymer protein, IAminoAcid aaToAdd, IStrand strand,
            IAminoAcid aaToAddTo) {
        // then add the amino acid
        addAminoAcid(protein, aaToAdd, strand);
        // Now think about the protein back bone connection
        if (protein.getMonomerCount() == 0) {
            // make the connection between that aminoAcid's C-terminus and the
            // protein's N-terminus
            protein.addBond(aaToAdd.getBuilder().newInstance(IBond.class, aaToAddTo.getNTerminus(),
                    aaToAdd.getCTerminus(), IBond.Order.SINGLE));
        } // else : no current N-terminus, so nothing special to do
        return protein;
    }
1151338
function modify( $tpl, $operatorName, $operatorParameters,
                     $rootNamespace, $currentNamespace, &$operatorValue, $namedParameters, $placement )
    {
        $functionName = $namedParameters['function_name'];
        $functionParameters = $namedParameters['function_parameters'];

        if ( $operatorName == $this->Fetch )
        {
            $moduleName = $namedParameters['module_name'];
            $result = eZFunctionHandler::execute( $moduleName, $functionName, $functionParameters );
            $operatorValue = $result;
        }
        else if ( $operatorName == $this->FetchAlias )
        {
            $result = eZFunctionHandler::executeAlias( $functionName, $functionParameters );
            $operatorValue = $result;
        }
    }
1321646
def _init_compile_patterns(optional_attrs):
        """"""
        attr2cmp = {}
        if optional_attrs is None:
            return attr2cmp
        # "peptidase inhibitor complex" EXACT [GOC:bf, GOC:pr]
        # "blood vessel formation from pre-existing blood vessels" EXACT systematic_synonym []
        # "mitochondrial inheritance" EXACT []
        # "tricarboxylate transport protein" RELATED [] {comment="WIkipedia:Mitochondrial_carrier"}
        if 'synonym' in optional_attrs:
            attr2cmp['synonym'] = re.compile(r'"(\S.*\S)" ([A-Z]+) (.*)\[(.*)\](.*)$')
            attr2cmp['synonym nt'] = cx.namedtuple("synonym", "text scope typename dbxrefs")
        # Wikipedia:Zygotene
        # Reactome:REACT_27267 "DHAP from Ery4P and PEP, Mycobacterium tuberculosis"
        if 'xref' in optional_attrs:
            attr2cmp['xref'] = re.compile(r'^(\S+:\s*\S+)\b(.*)$')
        return attr2cmp
119720
private ProtoNetwork stage1(final ProtoNetwork pn) {
        beginStage(PHASE3_STAGE1_HDR, "1", NUM_PHASES);

        final StringBuilder bldr = new StringBuilder();

        // Load the pfam resource from the resource index.
        Index resourceIndex = ResourceIndex.INSTANCE.getIndex();
        ResourceLocation pfResource = resourceIndex.getProteinFamilyResource();

        if (pfResource == null || pfResource.getResourceLocation() == null) {
            getPhaseConfiguration().setInjectProteinFamilies(false);
            stageError("Resource location for protein family is not set in " +
                    "resource index, disabling protein family expansion.");
            markEndStage(bldr);
            return pn;
        }

        if (!withProteinFamilyInjection()) {
            bldr.append(PF_INJECTION_DISABLED);
            markEndStage(bldr);
            stageOutput(bldr.toString());
            return pn;
        }

        String pfLocation = pfResource.getResourceLocation();
        File pfamResource = null;
        final ResourceType pfamType = fromLocation(pfLocation);
        try {
            ResolvedResource resolvedResource =
                    cache.resolveResource(pfamType, pfLocation);
            pfamResource = resolvedResource.getCacheResourceCopy();
        } catch (ResourceDownloadError e) {
            return failProteinFamilies(pn, bldr, pfLocation,
                    e.getUserFacingMessage());
        }

        // Fail if the protein family file is not readable
        if (!pfamResource.canRead()) {
            stageError(INPUT_FILE_UNREADABLE + pfamResource);
            failUsage();
        }

        stageOutput("Processing protein families");
        long t1 = currentTimeMillis();
        final Stage1Output output;
        if (pfamType == BEL) {
            output = p1.stage1BELValidation(pfamResource);
        } else {
            output = p1.stage1XBELValidation(pfamResource);
        }

        if (output.hasValidationErrors()) {
            for (final ValidationError error : output.getValidationErrors()) {
                stageError(error.getUserFacingMessage());
            }
            bail(NO_VALID_DOCUMENTS);
            return pn; // Dead code
        }
        if (output.hasConversionError()) {
            stageError(output.getConversionError().getUserFacingMessage());
            bail(NO_CONVERTED_DOCUMENTS);
            return pn; // Dead code
        }
        if (output.getSymbolWarning() != null) {
            stageError(output.getSymbolWarning().getUserFacingMessage());
        }
        long t2 = currentTimeMillis();
        Document pfDoc = output.getDocument();

        bldr.setLength(0);
        markTime(bldr, t1, t2);
        stageOutput(bldr.toString());

        stageOutput("Pruning protein families");
        boolean expand = withProteinFamilyExpansion();
        t1 = currentTimeMillis();
        DocumentModificationResult r = p3.pruneFamilies(expand, pfDoc, pn);
        t2 = currentTimeMillis();

        bldr.setLength(0);
        markTime(bldr, t1, t2);
        stageOutput(bldr.toString());

        if (r.isFailure()) {
            for (final String error : r.getErrors()) {
                stageError(error);
            }
            return pn;
        }
        for (final String warning : r.getWarnings()) {
            stageError(warning);
        }

        if (r.getRemainingStatements() == 0) {
            bldr.setLength(0);
            bldr.append("No statements remain after pruning");
            markEndStage(bldr);
            stageOutput(bldr.toString());
            return pn;
        }

        bldr.setLength(0);
        bldr.append(r.getRemainingStatements());
        bldr.append(" of ");
        bldr.append(r.getTotalStatements());
        bldr.append(" statements remain after pruning");
        stageOutput(bldr.toString());

        stageOutput("Inferring protein family relationships");
        t1 = currentTimeMillis();
        r = p3.inferFamilies(pfDoc, pn);
        t2 = currentTimeMillis();

        bldr.setLength(0);
        markTime(bldr, t1, t2);
        stageOutput(bldr.toString());

        if (r.isFailure()) {
            for (final String error : r.getErrors()) {
                stageError(error);
            }
            return pn;
        }
        for (final String warning : r.getWarnings()) {
            stageError(warning);
        }

        bldr.setLength(0);
        if (r.getDeltaStatements() == 0) {
            bldr.append("No statements inferred for protein families");
        } else {
            bldr.append(r.getDeltaStatements());
            bldr.append(" of ");
            bldr.append(r.getTotalStatements());
            bldr.append(" statements inferred for protein families");
        }
        stageOutput(bldr.toString());

        stageOutput("Compiling pruned protein families");
        t1 = currentTimeMillis();
        ProtoNetwork pfpn = p3.compile(pfDoc);
        t2 = currentTimeMillis();

        bldr.setLength(0);
        markTime(bldr, t1, t2);
        stageOutput(bldr.toString());

        if (withDebug()) {
            final String rootpath = artifactPath.getAbsolutePath();
            final String pfpath = asPath(rootpath, PRUNED_PF_NAME);
            createDirectories(pfpath);

            try {
                TextProtoNetworkExternalizer textExternalizer =
                        new TextProtoNetworkExternalizer();
                textExternalizer.writeProtoNetwork(pfpn, pfpath);
            } catch (ProtoNetworkError e) {
                stageError(e.getUserFacingMessage());
            }
        }

        stageOutput("Merging proto-networks");
        t1 = currentTimeMillis();
        try {

            p3.merge(pn, pfpn);

            // Change the input proto-network descriptor to merged network
            ProtoNetworkExternalizer pne = new BinaryProtoNetworkExternalizer();
            final String artpath = artifactPath.getAbsolutePath();
            final String s1path = asPath(artpath, STAGE1_OUTPUT);
            createDirectoryArtifact(artifactPath, STAGE1_OUTPUT);
            pne.writeProtoNetwork(pn, s1path);

            // if debug, then save the text-based merged network
            if (withDebug()) {
                TextProtoNetworkExternalizer textExternalizer =
                        new TextProtoNetworkExternalizer();
                textExternalizer.writeProtoNetwork(pn, s1path);
            }
        } catch (ProtoNetworkError e) {
            stageError(e.getUserFacingMessage());
            bail(FAILED_TO_MERGE_PROTO_NETWORKS);
            return pn; // Dead code
        }
        t2 = currentTimeMillis();

        bldr.setLength(0);
        markTime(bldr, t1, t2);
        markEndStage(bldr);
        stageOutput(bldr.toString());

        return pn;
    }
1053895
def dalignbedannot2daggbyquery(cfg):
    
    datatmpd=cfg['datatmpd']

    dalignbedannot=del_Unnamed(pd.read_csv(cfg['dalignbedannotp'],sep='\t',low_memory=False))
    
    daggbyqueryp=f'{datatmpd}/10_daggbyquery.tsv'      
    logging.info(basename(daggbyqueryp))
    if not exists(daggbyqueryp) or cfg['force']:
        dalignbedannot=dfliststr2dflist(dalignbedannot,
                                ['type', 'gene name', 'gene id', 'transcript id', 'protein id', 'exon id'],
                                colfmt='tuple')    
        dalignbedannot['alternate alignments count']=1
        import itertools
        from rohan.dandage.io_sets import unique
        def unique_dropna(l): return unique(l,drop='nan')
        def merge_unique_dropna(l): return unique(list(itertools.chain(*l)),drop='nan')
        cols2aggf={'id':unique_dropna,
         'type':merge_unique_dropna,
         'gene name':merge_unique_dropna,
         'gene id':merge_unique_dropna,
         'transcript id':merge_unique_dropna,
         'protein id':merge_unique_dropna,
         'exon id':merge_unique_dropna,
         'region':unique_dropna,
         'alternate alignments count':sum,
        }
        daggbyquery=dalignbedannot.groupby('query id').agg(cols2aggf)
        daggbyquery.to_csv(daggbyqueryp,sep='\t')
        daggbyquery.to_csv(cfg['dalignannotedp'],sep='\t')
    return cfg
822974
private Group getNewGroup(String recordName,Character aminoCode1, long seq_id,String groupCode3) {

		Group g = ChemCompGroupFactory.getGroupFromChemCompDictionary(groupCode3);
		if ( g != null && !g.getChemComp().isEmpty()) {
			if ( g instanceof AminoAcidImpl) {
				AminoAcidImpl aa = (AminoAcidImpl) g;
				aa.setId(seq_id);
			} else if ( g instanceof NucleotideImpl) {
				NucleotideImpl nuc =  (NucleotideImpl) g;
				nuc.setId(seq_id);
			} else if ( g instanceof HetatomImpl) {
				HetatomImpl het = (HetatomImpl)g;
				het.setId(seq_id);
			}
			return g;
		}



		Group group;
		if ( recordName.equals("ATOM") ) {
			if (StructureTools.isNucleotide(groupCode3))  {
				// it is a nucleotide
				NucleotideImpl nu = new NucleotideImpl();
				group = nu;
				nu.setId(seq_id);

			} else if (aminoCode1==null || aminoCode1 == StructureTools.UNKNOWN_GROUP_LABEL){
				HetatomImpl h = new HetatomImpl();
				h.setId(seq_id);
				group = h;

			} else {
				AminoAcidImpl aa = new AminoAcidImpl() ;
				aa.setAminoType(aminoCode1);
				aa.setId(seq_id);
				group = aa ;
			}
		}
		else {
			if (StructureTools.isNucleotide(groupCode3))  {
				// it is a nucleotide
				NucleotideImpl nu = new NucleotideImpl();
				group = nu;
				nu.setId(seq_id);
			}
			else if (aminoCode1 != null ) {
				AminoAcidImpl aa = new AminoAcidImpl() ;
				aa.setAminoType(aminoCode1);
				aa.setId(seq_id);
				group = aa ;
			} else {
				HetatomImpl h = new HetatomImpl();
				h.setId(seq_id);
				group = h;
			}
		}
		return  group ;
	}