<commit_before>"""
###############################################################################
Core:  Core Data Class
###############################################################################
"""
import string, random
import scipy as sp
import scipy.constants
from OpenPNM.Base import logging, Tools
from OpenPNM.Base import ModelsDict
logger = logging.getLogger()
from OpenPNM.Base import Controller
ctrl = Controller()

class Core(dict):
    r"""
    Contains OpenPNM specificmethods for working with the data in the dictionaries
    """

    def __new__(typ, *args, **kwargs):
        obj = dict.__new__(typ, *args, **kwargs)
        obj.update({'pore.all': sp.array([], ndmin=1, dtype=bool)})
        obj.update({'throat.all': sp.array([], ndmin=1, dtype=bool)})
        # Initialize phase, physics, and geometry tracking lists
        obj._name = None
        obj._ctrl = {}
        obj._phases = []
        obj._geometries = []
        obj._physics = []
        obj._net = None
        obj._parent = None
        # Initialize ordered dict for storing property models
        obj.models = ModelsDict()
        return obj

    def __init__(self, name=None, **kwargs):
        super().__init__()
        logger.debug('Initializing Core class')
        self.name = name
        self.controller = ctrl

    def __repr__(self):
        return '<%s.%s object at %s>' % (
            self.__class__.__module__,
            self.__class__.__name__,
            hex(id(self)))

    def __eq__(self,other):
        if hex(id(self)) == hex(id(other)):
            return True
        else:
            return False

    def __setitem__(self,key,value):
        r"""
        This is a subclass of the default __setitem__ behavior.  The main aim
        is to limit what type and shape of data can be written to protect
        the integrity of the network.


        Example
        -------
        >>> import OpenPNM
        >>> pn = OpenPNM.Network.TestNet()
        >>> pn['pore.example_property'] = 100
        >>> pn['pore.example_property'][0]
        100

        """
        #Enforce correct dict naming
        element = key.split('.')[0]
        if (element != 'pore') and (element != 'throat'):
            print('Array name \''+key+'\' does not begin with \'pore\' or \'throat\'')
            return
        #Convert value to an ndarray
        value = sp.array(value,ndmin=1)
        #Skip checks for 'coords', 'conns'
        if (key == 'pore.coords') or (key == 'throat.conns'):
            super(Core, self).__setitem__(key,value)
            return
        #Skip checks for protected props, and prevent changes if defined
        if key.split('.')[1] in ['all']:
            if key in self.keys():
                if sp.shape(self[key]) == (0,):
                    logger.debug(key+' is being defined.')
                    super(Core, self).__setitem__(key,value)
                else:
                    logger.warning(key+' is already defined.')
                    pass
            else:
                logger.debug(key+' is being defined.')
                super(Core, self).__setitem__(key,value)
            return
        #Write value to dictionary
        if sp.shape(value)[0] == 1:  # If value is scalar
            logger.debug('Broadcasting scalar value into vector: '+key)
            value = sp.ones((self._count(element),),dtype=value.dtype)*value
            super(Core, self).__setitem__(key,value)
        elif sp.shape(value)[0] == self._count(element):
            logger.debug('Updating vector: '+key)
            super(Core, self).__setitem__(key,value)
        else:
            if self._count(element) == 0:
                self.update({key:value})
            else:
                logger.warning('Cannot write vector with an array of the wrong length: '+key)
                pass

    def _set_ctrl(self,controller):
        if self.name in controller.keys():
            raise Exception('An object with that name is already present in simulation')
        self._ctrl = controller
        controller.update({self.name: self})

    def _get_ctrl(self):
        return self._ctrl

    controller = property(_get_ctrl,_set_ctrl)

    def _set_name(self,name):
        if name in self.controller.keys():
            raise Exception('An object named '+name+' already exists')
        elif name is None:
            name = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(5))
            name = self.__module__.split('.')[-1].strip('__') + '_' + name
        elif self._name is not None:
            logger.info('Changing the name of '+self.name+' to '+name)
            # Check if name collides with any arrays in the simulation
            objs = self._simulation()
            for item in objs:
                keys = [key.split('.')[-1] for key in item.keys()]
                if name in keys:
                    raise Exception('That name is already in use as an array name')
            for item in objs:
                if 'pore.'+self.name in item.keys():
                    item['pore.'+name] = item.pop('pore.'+self.name)
                if 'throat.'+self.name in item.keys():
                    item['throat.'+name] = item.pop('throat.'+self.name)
            self._ctrl[name] = self._ctrl.pop(self.name)
        self._name = name

    def _get_name(self):
        return self._name

    name = property(_get_name,_set_name)

    def _simulation(self):
        temp = []
        temp += [self._net]
        temp += self._net._phases
        temp += self._net._geometries
        temp += self._net._physics
        return temp<commit_msg>A few changes to error messages in Core<commit_after>"""
###############################################################################
Core:  Core Data Class
###############################################################################
"""
import string, random
import scipy as sp
import scipy.constants
from OpenPNM.Base import logging, Tools
from OpenPNM.Base import ModelsDict
logger = logging.getLogger()
from OpenPNM.Base import Controller
ctrl = Controller()

class Core(dict):
    r"""
    Contains OpenPNM specificmethods for working with the data in the dictionaries
    """

    def __new__(typ, *args, **kwargs):
        obj = dict.__new__(typ, *args, **kwargs)
        obj.update({'pore.all': sp.array([], ndmin=1, dtype=bool)})
        obj.update({'throat.all': sp.array([], ndmin=1, dtype=bool)})
        # Initialize phase, physics, and geometry tracking lists
        obj._name = None
        obj._ctrl = {}
        obj._phases = []
        obj._geometries = []
        obj._physics = []
        obj._net = None
        obj._parent = None
        # Initialize ordered dict for storing property models
        obj.models = ModelsDict()
        return obj

    def __init__(self, name=None, **kwargs):
        super().__init__()
        logger.debug('Initializing Core class')
        self.name = name
        self.controller = ctrl

    def __repr__(self):
        return '<%s.%s object at %s>' % (
            self.__class__.__module__,
            self.__class__.__name__,
            hex(id(self)))

    def __eq__(self,other):
        if hex(id(self)) == hex(id(other)):
            return True
        else:
            return False

    def __setitem__(self,key,value):
        r"""
        This is a subclass of the default __setitem__ behavior.  The main aim
        is to limit what type and shape of data can be written to protect
        the integrity of the network.


        Example
        -------
        >>> import OpenPNM
        >>> pn = OpenPNM.Network.TestNet()
        >>> pn['pore.example_property'] = 100
        >>> pn['pore.example_property'][0]
        100

        """
        #Enforce correct dict naming
        element = key.split('.')[0]
        if (element != 'pore') and (element != 'throat'):
            print('Array name \''+key+'\' does not begin with \'pore\' or \'throat\'')
            return
        #Convert value to an ndarray
        value = sp.array(value,ndmin=1)
        #Skip checks for 'coords', 'conns'
        if (key == 'pore.coords') or (key == 'throat.conns'):
            super(Core, self).__setitem__(key,value)
            return
        #Skip checks for protected props, and prevent changes if defined
        if key.split('.')[1] in ['all']:
            if key in self.keys():
                if sp.shape(self[key]) == (0,):
                    logger.debug(key+' is being defined.')
                    super(Core, self).__setitem__(key,value)
                else:
                    logger.warning(key+' is already defined.')
                    pass
            else:
                logger.debug(key+' is being defined.')
                super(Core, self).__setitem__(key,value)
            return
        #Write value to dictionary
        if sp.shape(value)[0] == 1:  # If value is scalar
            logger.debug('Broadcasting scalar value into vector: '+key)
            value = sp.ones((self._count(element),),dtype=value.dtype)*value
            super(Core, self).__setitem__(key,value)
        elif sp.shape(value)[0] == self._count(element):
            logger.debug('Updating vector: '+key)
            super(Core, self).__setitem__(key,value)
        else:
            if self._count(element) == 0:
                self.update({key:value})
            else:
                logger.warning('Cannot write vector with an array of the wrong length: '+key)
                pass

    def _set_ctrl(self,controller):
        if self.name in controller.keys():
            raise Exception('An object named '+self.name+' is already present in simulation')
        self._ctrl = controller
        controller.update({self.name: self})

    def _get_ctrl(self):
        return self._ctrl

    controller = property(_get_ctrl,_set_ctrl)

    def _set_name(self,name):
        if name in self.controller.keys():
            raise Exception('An object named '+name+' already exists')
        elif name is None:
            name = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(5))
            name = self.__module__.split('.')[-1].strip('__') + '_' + name
        elif self._name is not None:
            logger.info('Changing the name of '+self.name+' to '+name)
            # Check if name collides with any arrays in the simulation
            objs = self._simulation()
            for item in objs:
                keys = [key.split('.')[-1] for key in item.keys()]
                if name in keys:
                    raise Exception(name+' is already in use as an array name')
            for item in objs:
                if 'pore.'+self.name in item.keys():
                    item['pore.'+name] = item.pop('pore.'+self.name)
                if 'throat.'+self.name in item.keys():
                    item['throat.'+name] = item.pop('throat.'+self.name)
            self._ctrl[name] = self._ctrl.pop(self.name)
        self._name = name

    def _get_name(self):
        return self._name

    name = property(_get_name,_set_name)

    def _simulation(self):
        temp = []
        temp += [self._net]
        temp += self._net._phases
        temp += self._net._geometries
        temp += self._net._physics
        return temp
{'fraction_non_alphanumeric': 0.14678088845712267, 'fraction_numerical': 0.003532632694515588, 'mean_word_length': 2.0221510541766747, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 29, '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': '3708612', 'n_tokens_mistral': 3198, 'n_tokens_neox': 3078, 'n_words': 880}