<commit_before># datadict.py
"""Access dicom dictionary information"""
#
# Copyright (c) 2008 <NAME>
# This file is part of pydicom, relased under an MIT license.
#    See the file license.txt included with this distribution, also
#    available at http://pydicom.googlecode.com
#
import logging
logger = logging.getLogger("pydicom")
from dicom.tag import Tag
from dicom._dicom_dict import DicomDictionary  # the actual dict of {tag: (VR, VM, name, isRetired), tag:...}
from dicom._dicom_dict import RepeatersDictionary # those with tags like "(50xx, 0005)"

# Generate mask dict for checking repeating groups etc.
# Map a true bitwise mask to the DICOM mask with "x"'s in it.
masks = {}
for mask_x in RepeatersDictionary:
    # mask1 is XOR'd to see that all non-"x" bits are identical (XOR result = 0 if bits same)
    #      then AND those out with 0 bits at the "x" ("we don't care") location using mask2
    mask1 = long(mask_x.replace("x", "0"),16)
    mask2 = long("".join(["F0"[c=="x"] for c in mask_x]),16)
    masks[mask_x] = (mask1, mask2)

# For shorter naming of dicom member elements, put an entry here
#   (longer naming can also still be used)
# The descriptive name must start with the long version (not replaced if internal)
shortNames = [("BeamLimitingDevice", "BLD"),
              ("RTBeamLimitingDevice", "RTBLD"),
              ("ControlPoint", "CP"),
              ("Referenced", "Refd")
             ]

def mask_match(tag):
    for mask_x, (mask1, mask2) in masks.items():
        if (tag ^ mask1) & mask2 == 0:
            return mask_x
    return None
    
def get_entry(tag):
    """Return the tuple (VR, VM, name, isRetired) from the DICOM dictionary
    
    If the entry is not in the main dictionary, check the masked ones,
    e.g. repeating groups like 50xx, etc.
    """
    tag = Tag(tag)
    try:
        return DicomDictionary[tag]
    except KeyError:
        mask_x = mask_match(tag)
        if mask_x:
            return RepeatersDictionary[mask_x]
        else:
            raise KeyError, "Tag %s not found in DICOM dictionary" % Tag(tag)
        
def dictionaryDescription(tag):
    """Return the descriptive text for the given dicom tag."""
    return get_entry(tag)[2]

def dictionaryVM(tag):
    """Return the dicom value multiplicity for the given dicom tag."""
    return get_entry(tag)[1]

def dictionaryVR(tag):
    """Return the dicom value representation for the given dicom tag."""
    return get_entry(tag)[0]

def dictionaryHasTag(tag):
    """Return True if the dicom dictionary has an entry for the given tag."""
    return DicomDictionary.has_key(tag)

import string
normTable = string.maketrans('','')

def CleanName(tag):
    """Return the dictionary descriptive text string but without bad characters.
    
    Used for e.g. *named tags* of Dataset instances.
    
    """
    tag = Tag(tag)  # make sure is not an int
    if not DicomDictionary.has_key(tag): # can't name it - not in dictionary
        if tag.element == 0:             #  (unless is implied group length versions < 3)
            return "GroupLength"
        else:
            return ""
    s = dictionaryDescription(tag)    # Descriptive name in dictionary
    # remove blanks and nasty characters
    s = s.translate(normTable, r""" !@#$%^&*(),;:.?\|{}[]+-="'/""")
    
    # Take "Sequence" out of name as more natural sounding
    # e..g "BeamSequence"->"Beams"; "ReferencedImageBoxSequence"->"ReferencedImageBoxes"
    # 'Other Patient ID' exists as single value AND as sequence so check for it and leave 'Sequence' in
    if dictionaryVR(tag) == "SQ" and not s.startswith("Other Patient ID"):
        if s[-8:] == "Sequence": 
            s = s[:-8]+"s"
        if s[-2:] == "ss":
            s = s[:-1]
        if s[-6:] == "Studys":
            s = s[:-2]+"ies"
        if s[-2:] == "xs":
            s = s[:-1] + "es"
    return s

# Provide for the 'reverse' lookup. Given clean name, what is the tag?
logger.debug("Reversing DICOM dictionary so can look up tag from a name...")
NameDict = dict([(CleanName(tag), tag) for tag in DicomDictionary])<commit_msg>Bug in previous bug fix for OtherPatientIDs. Corrected here.<commit_after># datadict.py
"""Access dicom dictionary information"""
#
# Copyright (c) 2008 <NAME>
# This file is part of pydicom, relased under an MIT license.
#    See the file license.txt included with this distribution, also
#    available at http://pydicom.googlecode.com
#
import logging
logger = logging.getLogger("pydicom")
from dicom.tag import Tag
from dicom._dicom_dict import DicomDictionary  # the actual dict of {tag: (VR, VM, name, isRetired), tag:...}
from dicom._dicom_dict import RepeatersDictionary # those with tags like "(50xx, 0005)"

# Generate mask dict for checking repeating groups etc.
# Map a true bitwise mask to the DICOM mask with "x"'s in it.
masks = {}
for mask_x in RepeatersDictionary:
    # mask1 is XOR'd to see that all non-"x" bits are identical (XOR result = 0 if bits same)
    #      then AND those out with 0 bits at the "x" ("we don't care") location using mask2
    mask1 = long(mask_x.replace("x", "0"),16)
    mask2 = long("".join(["F0"[c=="x"] for c in mask_x]),16)
    masks[mask_x] = (mask1, mask2)

# For shorter naming of dicom member elements, put an entry here
#   (longer naming can also still be used)
# The descriptive name must start with the long version (not replaced if internal)
shortNames = [("BeamLimitingDevice", "BLD"),
              ("RTBeamLimitingDevice", "RTBLD"),
              ("ControlPoint", "CP"),
              ("Referenced", "Refd")
             ]

def mask_match(tag):
    for mask_x, (mask1, mask2) in masks.items():
        if (tag ^ mask1) & mask2 == 0:
            return mask_x
    return None
    
def get_entry(tag):
    """Return the tuple (VR, VM, name, isRetired) from the DICOM dictionary
    
    If the entry is not in the main dictionary, check the masked ones,
    e.g. repeating groups like 50xx, etc.
    """
    tag = Tag(tag)
    try:
        return DicomDictionary[tag]
    except KeyError:
        mask_x = mask_match(tag)
        if mask_x:
            return RepeatersDictionary[mask_x]
        else:
            raise KeyError, "Tag %s not found in DICOM dictionary" % Tag(tag)
        
def dictionaryDescription(tag):
    """Return the descriptive text for the given dicom tag."""
    return get_entry(tag)[2]

def dictionaryVM(tag):
    """Return the dicom value multiplicity for the given dicom tag."""
    return get_entry(tag)[1]

def dictionaryVR(tag):
    """Return the dicom value representation for the given dicom tag."""
    return get_entry(tag)[0]

def dictionaryHasTag(tag):
    """Return True if the dicom dictionary has an entry for the given tag."""
    return DicomDictionary.has_key(tag)

import string
normTable = string.maketrans('','')

def CleanName(tag):
    """Return the dictionary descriptive text string but without bad characters.
    
    Used for e.g. *named tags* of Dataset instances.
    
    """
    tag = Tag(tag)  # make sure is not an int
    if not DicomDictionary.has_key(tag): # can't name it - not in dictionary
        if tag.element == 0:             #  (unless is implied group length versions < 3)
            return "GroupLength"
        else:
            return ""
    s = dictionaryDescription(tag)    # Descriptive name in dictionary
    # remove blanks and nasty characters
    s = s.translate(normTable, r""" !@#$%^&*(),;:.?\|{}[]+-="'/""")
    
    # Take "Sequence" out of name as more natural sounding
    # e..g "BeamSequence"->"Beams"; "ReferencedImageBoxSequence"->"ReferencedImageBoxes"
    # 'Other Patient ID' exists as single value AND as sequence so check for it and leave 'Sequence' in
    if dictionaryVR(tag) == "SQ" and not s.startswith("OtherPatientIDs"):
        if s[-8:] == "Sequence": 
            s = s[:-8]+"s"
        if s[-2:] == "ss":
            s = s[:-1]
        if s[-6:] == "Studys":
            s = s[:-2]+"ies"
        if s[-2:] == "xs":
            s = s[:-1] + "es"
    return s

# Provide for the 'reverse' lookup. Given clean name, what is the tag?
logger.debug("Reversing DICOM dictionary so can look up tag from a name...")
NameDict = dict([(CleanName(tag), tag) for tag in DicomDictionary])
{'fraction_non_alphanumeric': 0.1203591361320068, 'fraction_numerical': 0.010677020140742538, 'mean_word_length': 2.9010884997633695, 'pattern_counts': {'":': 8, '<': 7, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '205829', 'n_tokens_mistral': 2622, 'n_tokens_neox': 2512, 'n_words': 939}