prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>0006_auto_20150827_1019.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('formbuilder', '0005_auto_20150826_1600'),
]
operations = [<|fim▁hole|> model_name='choiceanswer',
name='option',
),
migrations.AddField(
model_name='choiceanswer',
name='choices',
field=models.ManyToManyField(related_name='answers', to='formbuilder.Option'),
),
migrations.AddField(
model_name='choiceanswer',
name='other',
field=models.TextField(blank=True),
),
migrations.AddField(
model_name='choiceanswer',
name='question',
field=models.ForeignKey(related_name='answers', to='formbuilder.Choice', null=True),
),
]<|fim▁end|> | migrations.RemoveField( |
<|file_name|>0006_auto_20150827_1019.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
<|fim_middle|>
<|fim▁end|> | dependencies = [
('formbuilder', '0005_auto_20150826_1600'),
]
operations = [
migrations.RemoveField(
model_name='choiceanswer',
name='option',
),
migrations.AddField(
model_name='choiceanswer',
name='choices',
field=models.ManyToManyField(related_name='answers', to='formbuilder.Option'),
),
migrations.AddField(
model_name='choiceanswer',
name='other',
field=models.TextField(blank=True),
),
migrations.AddField(
model_name='choiceanswer',
name='question',
field=models.ForeignKey(related_name='answers', to='formbuilder.Choice', null=True),
),
] |
<|file_name|>chrome_cache.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the Google Chrome Cache files event formatter."""
import unittest
from plaso.formatters import chrome_cache
from tests.formatters import test_lib
class ChromeCacheEntryEventFormatterTest(test_lib.EventFormatterTestCase):
"""Tests for the Chrome Cache entry event formatter."""
def testInitialization(self):
"""Tests the initialization."""
event_formatter = chrome_cache.ChromeCacheEntryEventFormatter()
self.assertIsNotNone(event_formatter)
def testGetFormatStringAttributeNames(self):
"""Tests the GetFormatStringAttributeNames function."""<|fim▁hole|>
expected_attribute_names = [u'original_url']
self._TestGetFormatStringAttributeNames(
event_formatter, expected_attribute_names)
# TODO: add test for GetMessages.
if __name__ == '__main__':
unittest.main()<|fim▁end|> | event_formatter = chrome_cache.ChromeCacheEntryEventFormatter() |
<|file_name|>chrome_cache.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the Google Chrome Cache files event formatter."""
import unittest
from plaso.formatters import chrome_cache
from tests.formatters import test_lib
class ChromeCacheEntryEventFormatterTest(test_lib.EventFormatterTestCase):
<|fim_middle|>
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | """Tests for the Chrome Cache entry event formatter."""
def testInitialization(self):
"""Tests the initialization."""
event_formatter = chrome_cache.ChromeCacheEntryEventFormatter()
self.assertIsNotNone(event_formatter)
def testGetFormatStringAttributeNames(self):
"""Tests the GetFormatStringAttributeNames function."""
event_formatter = chrome_cache.ChromeCacheEntryEventFormatter()
expected_attribute_names = [u'original_url']
self._TestGetFormatStringAttributeNames(
event_formatter, expected_attribute_names)
# TODO: add test for GetMessages. |
<|file_name|>chrome_cache.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the Google Chrome Cache files event formatter."""
import unittest
from plaso.formatters import chrome_cache
from tests.formatters import test_lib
class ChromeCacheEntryEventFormatterTest(test_lib.EventFormatterTestCase):
"""Tests for the Chrome Cache entry event formatter."""
def testInitialization(self):
<|fim_middle|>
def testGetFormatStringAttributeNames(self):
"""Tests the GetFormatStringAttributeNames function."""
event_formatter = chrome_cache.ChromeCacheEntryEventFormatter()
expected_attribute_names = [u'original_url']
self._TestGetFormatStringAttributeNames(
event_formatter, expected_attribute_names)
# TODO: add test for GetMessages.
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | """Tests the initialization."""
event_formatter = chrome_cache.ChromeCacheEntryEventFormatter()
self.assertIsNotNone(event_formatter) |
<|file_name|>chrome_cache.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the Google Chrome Cache files event formatter."""
import unittest
from plaso.formatters import chrome_cache
from tests.formatters import test_lib
class ChromeCacheEntryEventFormatterTest(test_lib.EventFormatterTestCase):
"""Tests for the Chrome Cache entry event formatter."""
def testInitialization(self):
"""Tests the initialization."""
event_formatter = chrome_cache.ChromeCacheEntryEventFormatter()
self.assertIsNotNone(event_formatter)
def testGetFormatStringAttributeNames(self):
<|fim_middle|>
# TODO: add test for GetMessages.
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | """Tests the GetFormatStringAttributeNames function."""
event_formatter = chrome_cache.ChromeCacheEntryEventFormatter()
expected_attribute_names = [u'original_url']
self._TestGetFormatStringAttributeNames(
event_formatter, expected_attribute_names) |
<|file_name|>chrome_cache.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the Google Chrome Cache files event formatter."""
import unittest
from plaso.formatters import chrome_cache
from tests.formatters import test_lib
class ChromeCacheEntryEventFormatterTest(test_lib.EventFormatterTestCase):
"""Tests for the Chrome Cache entry event formatter."""
def testInitialization(self):
"""Tests the initialization."""
event_formatter = chrome_cache.ChromeCacheEntryEventFormatter()
self.assertIsNotNone(event_formatter)
def testGetFormatStringAttributeNames(self):
"""Tests the GetFormatStringAttributeNames function."""
event_formatter = chrome_cache.ChromeCacheEntryEventFormatter()
expected_attribute_names = [u'original_url']
self._TestGetFormatStringAttributeNames(
event_formatter, expected_attribute_names)
# TODO: add test for GetMessages.
if __name__ == '__main__':
<|fim_middle|>
<|fim▁end|> | unittest.main() |
<|file_name|>chrome_cache.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the Google Chrome Cache files event formatter."""
import unittest
from plaso.formatters import chrome_cache
from tests.formatters import test_lib
class ChromeCacheEntryEventFormatterTest(test_lib.EventFormatterTestCase):
"""Tests for the Chrome Cache entry event formatter."""
def <|fim_middle|>(self):
"""Tests the initialization."""
event_formatter = chrome_cache.ChromeCacheEntryEventFormatter()
self.assertIsNotNone(event_formatter)
def testGetFormatStringAttributeNames(self):
"""Tests the GetFormatStringAttributeNames function."""
event_formatter = chrome_cache.ChromeCacheEntryEventFormatter()
expected_attribute_names = [u'original_url']
self._TestGetFormatStringAttributeNames(
event_formatter, expected_attribute_names)
# TODO: add test for GetMessages.
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | testInitialization |
<|file_name|>chrome_cache.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the Google Chrome Cache files event formatter."""
import unittest
from plaso.formatters import chrome_cache
from tests.formatters import test_lib
class ChromeCacheEntryEventFormatterTest(test_lib.EventFormatterTestCase):
"""Tests for the Chrome Cache entry event formatter."""
def testInitialization(self):
"""Tests the initialization."""
event_formatter = chrome_cache.ChromeCacheEntryEventFormatter()
self.assertIsNotNone(event_formatter)
def <|fim_middle|>(self):
"""Tests the GetFormatStringAttributeNames function."""
event_formatter = chrome_cache.ChromeCacheEntryEventFormatter()
expected_attribute_names = [u'original_url']
self._TestGetFormatStringAttributeNames(
event_formatter, expected_attribute_names)
# TODO: add test for GetMessages.
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | testGetFormatStringAttributeNames |
<|file_name|>test_console.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from ..exceptions import ConsoleError
from . import mock
import pytest
console.raw_input=mock.raw_input
def test_prompt():
field=fields.Field("test_field", "test field", fields.Field.TYPE_TEXT_ONELINE, "this is a test field")
assert console.prompt(field)=="999"
def test_input_parser():
sys_args=['-f', 'myfile']
exts=["test"]
models=["test_model"]
assert console.input_parser(models, exts, sys_args)==["test_model","myfile","test"]
with pytest.raises(ConsoleError):
console.input_parser("", "", sys_args)<|fim▁end|> | from .. import console, fields |
<|file_name|>test_console.py<|end_file_name|><|fim▁begin|>from .. import console, fields
from ..exceptions import ConsoleError
from . import mock
import pytest
console.raw_input=mock.raw_input
def test_prompt():
<|fim_middle|>
def test_input_parser():
sys_args=['-f', 'myfile']
exts=["test"]
models=["test_model"]
assert console.input_parser(models, exts, sys_args)==["test_model","myfile","test"]
with pytest.raises(ConsoleError):
console.input_parser("", "", sys_args)
<|fim▁end|> | field=fields.Field("test_field", "test field", fields.Field.TYPE_TEXT_ONELINE, "this is a test field")
assert console.prompt(field)=="999" |
<|file_name|>test_console.py<|end_file_name|><|fim▁begin|>from .. import console, fields
from ..exceptions import ConsoleError
from . import mock
import pytest
console.raw_input=mock.raw_input
def test_prompt():
field=fields.Field("test_field", "test field", fields.Field.TYPE_TEXT_ONELINE, "this is a test field")
assert console.prompt(field)=="999"
def test_input_parser():
<|fim_middle|>
<|fim▁end|> | sys_args=['-f', 'myfile']
exts=["test"]
models=["test_model"]
assert console.input_parser(models, exts, sys_args)==["test_model","myfile","test"]
with pytest.raises(ConsoleError):
console.input_parser("", "", sys_args) |
<|file_name|>test_console.py<|end_file_name|><|fim▁begin|>from .. import console, fields
from ..exceptions import ConsoleError
from . import mock
import pytest
console.raw_input=mock.raw_input
def <|fim_middle|>():
field=fields.Field("test_field", "test field", fields.Field.TYPE_TEXT_ONELINE, "this is a test field")
assert console.prompt(field)=="999"
def test_input_parser():
sys_args=['-f', 'myfile']
exts=["test"]
models=["test_model"]
assert console.input_parser(models, exts, sys_args)==["test_model","myfile","test"]
with pytest.raises(ConsoleError):
console.input_parser("", "", sys_args)
<|fim▁end|> | test_prompt |
<|file_name|>test_console.py<|end_file_name|><|fim▁begin|>from .. import console, fields
from ..exceptions import ConsoleError
from . import mock
import pytest
console.raw_input=mock.raw_input
def test_prompt():
field=fields.Field("test_field", "test field", fields.Field.TYPE_TEXT_ONELINE, "this is a test field")
assert console.prompt(field)=="999"
def <|fim_middle|>():
sys_args=['-f', 'myfile']
exts=["test"]
models=["test_model"]
assert console.input_parser(models, exts, sys_args)==["test_model","myfile","test"]
with pytest.raises(ConsoleError):
console.input_parser("", "", sys_args)
<|fim▁end|> | test_input_parser |
<|file_name|>logutil.py<|end_file_name|><|fim▁begin|>#
# logutil.py
# A module containing means of interacting with log files.
#
import logging
import logging.handlers
import os
import time
from data_structures import enum
from config import get_config_value
LoggingSection = enum(
'CLIENT',
'CRAWLER',
'DATA',
'FRONTIER',
'TEST',
'UTILITIES',
)
#region Setup
logging.basicConfig(level=logging.INFO,
format='[%(asctime)s %(levelname)s] %(name)s::%(funcName)s - %(message)s',
datefmt='%x %X %Z')
module_dir = os.path.dirname(__file__)
logfile = os.path.join(module_dir, get_config_value('LOG', 'path'))
logdir = os.path.join(module_dir, get_config_value('LOG', 'dir'))<|fim▁hole|>
if not os.path.exists(logdir):
os.mkdir(logdir)
handler = logging.handlers.RotatingFileHandler(logfile,
maxBytes=8192,
backupCount=10, )
formatter = logging.Formatter('[%(asctime)s %(levelname)s] %(name)s::%(funcName)s - %(message)s')
formatter.datefmt = '%x %X %Z'
formatter.converter = time.gmtime
handler.setFormatter(formatter)
#endregion
def get_logger(section, name):
"""
Fetches a logger.
Arguments:
section (string): The section the logger is attributed to.
name (string): The name of the logger.
Returns:
The logger corresponding to the section and name provided.
"""
section_name = LoggingSection.reverse_mapping[section].lower()
logger = logging.getLogger('htresearch.{0}.{1}'.format(section_name, name))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
return logger<|fim▁end|> | |
<|file_name|>logutil.py<|end_file_name|><|fim▁begin|>#
# logutil.py
# A module containing means of interacting with log files.
#
import logging
import logging.handlers
import os
import time
from data_structures import enum
from config import get_config_value
LoggingSection = enum(
'CLIENT',
'CRAWLER',
'DATA',
'FRONTIER',
'TEST',
'UTILITIES',
)
#region Setup
logging.basicConfig(level=logging.INFO,
format='[%(asctime)s %(levelname)s] %(name)s::%(funcName)s - %(message)s',
datefmt='%x %X %Z')
module_dir = os.path.dirname(__file__)
logfile = os.path.join(module_dir, get_config_value('LOG', 'path'))
logdir = os.path.join(module_dir, get_config_value('LOG', 'dir'))
if not os.path.exists(logdir):
os.mkdir(logdir)
handler = logging.handlers.RotatingFileHandler(logfile,
maxBytes=8192,
backupCount=10, )
formatter = logging.Formatter('[%(asctime)s %(levelname)s] %(name)s::%(funcName)s - %(message)s')
formatter.datefmt = '%x %X %Z'
formatter.converter = time.gmtime
handler.setFormatter(formatter)
#endregion
def get_logger(section, name):
<|fim_middle|>
<|fim▁end|> | """
Fetches a logger.
Arguments:
section (string): The section the logger is attributed to.
name (string): The name of the logger.
Returns:
The logger corresponding to the section and name provided.
"""
section_name = LoggingSection.reverse_mapping[section].lower()
logger = logging.getLogger('htresearch.{0}.{1}'.format(section_name, name))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
return logger |
<|file_name|>logutil.py<|end_file_name|><|fim▁begin|>#
# logutil.py
# A module containing means of interacting with log files.
#
import logging
import logging.handlers
import os
import time
from data_structures import enum
from config import get_config_value
LoggingSection = enum(
'CLIENT',
'CRAWLER',
'DATA',
'FRONTIER',
'TEST',
'UTILITIES',
)
#region Setup
logging.basicConfig(level=logging.INFO,
format='[%(asctime)s %(levelname)s] %(name)s::%(funcName)s - %(message)s',
datefmt='%x %X %Z')
module_dir = os.path.dirname(__file__)
logfile = os.path.join(module_dir, get_config_value('LOG', 'path'))
logdir = os.path.join(module_dir, get_config_value('LOG', 'dir'))
if not os.path.exists(logdir):
<|fim_middle|>
handler = logging.handlers.RotatingFileHandler(logfile,
maxBytes=8192,
backupCount=10, )
formatter = logging.Formatter('[%(asctime)s %(levelname)s] %(name)s::%(funcName)s - %(message)s')
formatter.datefmt = '%x %X %Z'
formatter.converter = time.gmtime
handler.setFormatter(formatter)
#endregion
def get_logger(section, name):
"""
Fetches a logger.
Arguments:
section (string): The section the logger is attributed to.
name (string): The name of the logger.
Returns:
The logger corresponding to the section and name provided.
"""
section_name = LoggingSection.reverse_mapping[section].lower()
logger = logging.getLogger('htresearch.{0}.{1}'.format(section_name, name))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
return logger<|fim▁end|> | os.mkdir(logdir) |
<|file_name|>logutil.py<|end_file_name|><|fim▁begin|>#
# logutil.py
# A module containing means of interacting with log files.
#
import logging
import logging.handlers
import os
import time
from data_structures import enum
from config import get_config_value
LoggingSection = enum(
'CLIENT',
'CRAWLER',
'DATA',
'FRONTIER',
'TEST',
'UTILITIES',
)
#region Setup
logging.basicConfig(level=logging.INFO,
format='[%(asctime)s %(levelname)s] %(name)s::%(funcName)s - %(message)s',
datefmt='%x %X %Z')
module_dir = os.path.dirname(__file__)
logfile = os.path.join(module_dir, get_config_value('LOG', 'path'))
logdir = os.path.join(module_dir, get_config_value('LOG', 'dir'))
if not os.path.exists(logdir):
os.mkdir(logdir)
handler = logging.handlers.RotatingFileHandler(logfile,
maxBytes=8192,
backupCount=10, )
formatter = logging.Formatter('[%(asctime)s %(levelname)s] %(name)s::%(funcName)s - %(message)s')
formatter.datefmt = '%x %X %Z'
formatter.converter = time.gmtime
handler.setFormatter(formatter)
#endregion
def <|fim_middle|>(section, name):
"""
Fetches a logger.
Arguments:
section (string): The section the logger is attributed to.
name (string): The name of the logger.
Returns:
The logger corresponding to the section and name provided.
"""
section_name = LoggingSection.reverse_mapping[section].lower()
logger = logging.getLogger('htresearch.{0}.{1}'.format(section_name, name))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
return logger<|fim▁end|> | get_logger |
<|file_name|>test_comment.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import unittest
import pykintone
from pykintone.model import kintoneModel
import tests.envs as envs
class TestAppModelSimple(kintoneModel):
def __init__(self):
super(TestAppModelSimple, self).__init__()
self.my_key = ""
self.stringField = ""
class TestComment(unittest.TestCase):
<|fim▁hole|> def test_comment(self):
app = pykintone.load(envs.FILE_PATH).app()
model = TestAppModelSimple()
model.my_key = "comment_test"
model.stringField = "comment_test_now"
result = app.create(model)
self.assertTrue(result.ok) # confirm create the record to test comment
_record_id = result.record_id
# create comment
r_created = app.comment(_record_id).create("コメントのテスト")
self.assertTrue(r_created.ok)
# it requires Administrator user is registered in kintone
r_created_m = app.comment(_record_id).create("メンションのテスト", [("Administrator", "USER")])
self.assertTrue(r_created_m.ok)
# select comment
r_selected = app.comment(_record_id).select(True, 0, 10)
self.assertTrue(r_selected.ok)
self.assertTrue(2, len(r_selected.raw_comments))
comments = r_selected.comments()
self.assertTrue(1, len(comments[-1].mentions))
# delete comment
for c in comments:
r_deleted = app.comment(_record_id).delete(c.comment_id)
self.assertTrue(r_deleted.ok)
r_selected = app.comment(_record_id).select()
self.assertEqual(0, len(r_selected.raw_comments))
# done test
app.delete(_record_id)<|fim▁end|> | |
<|file_name|>test_comment.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import unittest
import pykintone
from pykintone.model import kintoneModel
import tests.envs as envs
class TestAppModelSimple(kintoneModel):
<|fim_middle|>
class TestComment(unittest.TestCase):
def test_comment(self):
app = pykintone.load(envs.FILE_PATH).app()
model = TestAppModelSimple()
model.my_key = "comment_test"
model.stringField = "comment_test_now"
result = app.create(model)
self.assertTrue(result.ok) # confirm create the record to test comment
_record_id = result.record_id
# create comment
r_created = app.comment(_record_id).create("コメントのテスト")
self.assertTrue(r_created.ok)
# it requires Administrator user is registered in kintone
r_created_m = app.comment(_record_id).create("メンションのテスト", [("Administrator", "USER")])
self.assertTrue(r_created_m.ok)
# select comment
r_selected = app.comment(_record_id).select(True, 0, 10)
self.assertTrue(r_selected.ok)
self.assertTrue(2, len(r_selected.raw_comments))
comments = r_selected.comments()
self.assertTrue(1, len(comments[-1].mentions))
# delete comment
for c in comments:
r_deleted = app.comment(_record_id).delete(c.comment_id)
self.assertTrue(r_deleted.ok)
r_selected = app.comment(_record_id).select()
self.assertEqual(0, len(r_selected.raw_comments))
# done test
app.delete(_record_id)
<|fim▁end|> | def __init__(self):
super(TestAppModelSimple, self).__init__()
self.my_key = ""
self.stringField = "" |
<|file_name|>test_comment.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import unittest
import pykintone
from pykintone.model import kintoneModel
import tests.envs as envs
class TestAppModelSimple(kintoneModel):
def __init__(self):
<|fim_middle|>
class TestComment(unittest.TestCase):
def test_comment(self):
app = pykintone.load(envs.FILE_PATH).app()
model = TestAppModelSimple()
model.my_key = "comment_test"
model.stringField = "comment_test_now"
result = app.create(model)
self.assertTrue(result.ok) # confirm create the record to test comment
_record_id = result.record_id
# create comment
r_created = app.comment(_record_id).create("コメントのテスト")
self.assertTrue(r_created.ok)
# it requires Administrator user is registered in kintone
r_created_m = app.comment(_record_id).create("メンションのテスト", [("Administrator", "USER")])
self.assertTrue(r_created_m.ok)
# select comment
r_selected = app.comment(_record_id).select(True, 0, 10)
self.assertTrue(r_selected.ok)
self.assertTrue(2, len(r_selected.raw_comments))
comments = r_selected.comments()
self.assertTrue(1, len(comments[-1].mentions))
# delete comment
for c in comments:
r_deleted = app.comment(_record_id).delete(c.comment_id)
self.assertTrue(r_deleted.ok)
r_selected = app.comment(_record_id).select()
self.assertEqual(0, len(r_selected.raw_comments))
# done test
app.delete(_record_id)
<|fim▁end|> | super(TestAppModelSimple, self).__init__()
self.my_key = ""
self.stringField = "" |
<|file_name|>test_comment.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import unittest
import pykintone
from pykintone.model import kintoneModel
import tests.envs as envs
class TestAppModelSimple(kintoneModel):
def __init__(self):
super(TestAppModelSimple, self).__init__()
self.my_key = ""
self.stringField = ""
class TestComment(unittest.TestCase):
<|fim_middle|>
<|fim▁end|> | def test_comment(self):
app = pykintone.load(envs.FILE_PATH).app()
model = TestAppModelSimple()
model.my_key = "comment_test"
model.stringField = "comment_test_now"
result = app.create(model)
self.assertTrue(result.ok) # confirm create the record to test comment
_record_id = result.record_id
# create comment
r_created = app.comment(_record_id).create("コメントのテスト")
self.assertTrue(r_created.ok)
# it requires Administrator user is registered in kintone
r_created_m = app.comment(_record_id).create("メンションのテスト", [("Administrator", "USER")])
self.assertTrue(r_created_m.ok)
# select comment
r_selected = app.comment(_record_id).select(True, 0, 10)
self.assertTrue(r_selected.ok)
self.assertTrue(2, len(r_selected.raw_comments))
comments = r_selected.comments()
self.assertTrue(1, len(comments[-1].mentions))
# delete comment
for c in comments:
r_deleted = app.comment(_record_id).delete(c.comment_id)
self.assertTrue(r_deleted.ok)
r_selected = app.comment(_record_id).select()
self.assertEqual(0, len(r_selected.raw_comments))
# done test
app.delete(_record_id)
|
<|file_name|>test_comment.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import unittest
import pykintone
from pykintone.model import kintoneModel
import tests.envs as envs
class TestAppModelSimple(kintoneModel):
def __init__(self):
super(TestAppModelSimple, self).__init__()
self.my_key = ""
self.stringField = ""
class TestComment(unittest.TestCase):
def test_comment(self):
<|fim_middle|>
<|fim▁end|> | app = pykintone.load(envs.FILE_PATH).app()
model = TestAppModelSimple()
model.my_key = "comment_test"
model.stringField = "comment_test_now"
result = app.create(model)
self.assertTrue(result.ok) # confirm create the record to test comment
_record_id = result.record_id
# create comment
r_created = app.comment(_record_id).create("コメントのテスト")
self.assertTrue(r_created.ok)
# it requires Administrator user is registered in kintone
r_created_m = app.comment(_record_id).create("メンションのテスト", [("Administrator", "USER")])
self.assertTrue(r_created_m.ok)
# select comment
r_selected = app.comment(_record_id).select(True, 0, 10)
self.assertTrue(r_selected.ok)
self.assertTrue(2, len(r_selected.raw_comments))
comments = r_selected.comments()
self.assertTrue(1, len(comments[-1].mentions))
# delete comment
for c in comments:
r_deleted = app.comment(_record_id).delete(c.comment_id)
self.assertTrue(r_deleted.ok)
r_selected = app.comment(_record_id).select()
self.assertEqual(0, len(r_selected.raw_comments))
# done test
app.delete(_record_id)
|
<|file_name|>test_comment.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import unittest
import pykintone
from pykintone.model import kintoneModel
import tests.envs as envs
class TestAppModelSimple(kintoneModel):
def <|fim_middle|>(self):
super(TestAppModelSimple, self).__init__()
self.my_key = ""
self.stringField = ""
class TestComment(unittest.TestCase):
def test_comment(self):
app = pykintone.load(envs.FILE_PATH).app()
model = TestAppModelSimple()
model.my_key = "comment_test"
model.stringField = "comment_test_now"
result = app.create(model)
self.assertTrue(result.ok) # confirm create the record to test comment
_record_id = result.record_id
# create comment
r_created = app.comment(_record_id).create("コメントのテスト")
self.assertTrue(r_created.ok)
# it requires Administrator user is registered in kintone
r_created_m = app.comment(_record_id).create("メンションのテスト", [("Administrator", "USER")])
self.assertTrue(r_created_m.ok)
# select comment
r_selected = app.comment(_record_id).select(True, 0, 10)
self.assertTrue(r_selected.ok)
self.assertTrue(2, len(r_selected.raw_comments))
comments = r_selected.comments()
self.assertTrue(1, len(comments[-1].mentions))
# delete comment
for c in comments:
r_deleted = app.comment(_record_id).delete(c.comment_id)
self.assertTrue(r_deleted.ok)
r_selected = app.comment(_record_id).select()
self.assertEqual(0, len(r_selected.raw_comments))
# done test
app.delete(_record_id)
<|fim▁end|> | __init__ |
<|file_name|>test_comment.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import unittest
import pykintone
from pykintone.model import kintoneModel
import tests.envs as envs
class TestAppModelSimple(kintoneModel):
def __init__(self):
super(TestAppModelSimple, self).__init__()
self.my_key = ""
self.stringField = ""
class TestComment(unittest.TestCase):
def <|fim_middle|>(self):
app = pykintone.load(envs.FILE_PATH).app()
model = TestAppModelSimple()
model.my_key = "comment_test"
model.stringField = "comment_test_now"
result = app.create(model)
self.assertTrue(result.ok) # confirm create the record to test comment
_record_id = result.record_id
# create comment
r_created = app.comment(_record_id).create("コメントのテスト")
self.assertTrue(r_created.ok)
# it requires Administrator user is registered in kintone
r_created_m = app.comment(_record_id).create("メンションのテスト", [("Administrator", "USER")])
self.assertTrue(r_created_m.ok)
# select comment
r_selected = app.comment(_record_id).select(True, 0, 10)
self.assertTrue(r_selected.ok)
self.assertTrue(2, len(r_selected.raw_comments))
comments = r_selected.comments()
self.assertTrue(1, len(comments[-1].mentions))
# delete comment
for c in comments:
r_deleted = app.comment(_record_id).delete(c.comment_id)
self.assertTrue(r_deleted.ok)
r_selected = app.comment(_record_id).select()
self.assertEqual(0, len(r_selected.raw_comments))
# done test
app.delete(_record_id)
<|fim▁end|> | test_comment |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):<|fim▁hole|> try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''<|fim▁end|> | |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
<|fim_middle|>
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
<|fim_middle|>
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg) |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
<|fim_middle|>
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | return __file__ |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
<|fim_middle|>
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | opts = ["volta_options"]
return opts |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
<|fim_middle|>
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | self.volta_core.configure() |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
<|fim_middle|>
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | if self.reader is None:
self.reader = AndroidReader()
return self.reader |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
<|fim_middle|>
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
<|fim_middle|>
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()] |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
<|fim_middle|>
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1 |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
<|fim_middle|>
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1 |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
<|fim_middle|>
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
<|fim_middle|>
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | return AndroidInfo() |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
<|fim_middle|>
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
<|fim_middle|>
<|fim▁end|> | def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = '' |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
<|fim_middle|>
<|fim▁end|> | self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = '' |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
<|fim_middle|>
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key) |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
<|fim_middle|>
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | self.reader = AndroidReader() |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
<|fim_middle|>
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | self.stats_reader = AndroidStatsReader() |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
<|fim_middle|>
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
<|fim_middle|>
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
<|fim_middle|>
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | logger.warning('There is no test performer process on the phone, interrupting test')
return 1 |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
<|fim_middle|>
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | logger.debug('Waiting for phone test to finish...')
return -1 |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
<|fim_middle|>
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | return self.volta_core.phone.test_performer.retcode |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def <|fim_middle|>(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | __init__ |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def <|fim_middle|>():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | get_key |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def <|fim_middle|>(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | get_available_options |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def <|fim_middle|>(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | configure |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def <|fim_middle|>(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | get_reader |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def <|fim_middle|>(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | get_stats_reader |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def <|fim_middle|>(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | prepare_test |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def <|fim_middle|>(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | start_test |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def <|fim_middle|>(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | is_test_finished |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def <|fim_middle|>(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | end_test |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def <|fim_middle|>(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | get_info |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def <|fim_middle|>(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def __init__(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | post_process |
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core, cfg, name):
self.stats_reader = None
self.reader = None
super(Plugin, self).__init__(core, cfg, name)
self.device = None
try:
self.cfg = cfg['volta_options']
for key, value in self.cfg.items():
if not isinstance(value, dict):
logger.debug('Malformed VoltaConfig key: %s value %s', key, value)
raise RuntimeError('Malformed VoltaConfig passed, key: %s. Should by dict' % key)
except AttributeError:
logger.error('Failed to read Volta config', exc_info=True)
self.volta_core = VoltaCore(self.cfg)
@staticmethod
def get_key():
return __file__
def get_available_options(self):
opts = ["volta_options"]
return opts
def configure(self):
self.volta_core.configure()
def get_reader(self):
if self.reader is None:
self.reader = AndroidReader()
return self.reader
def get_stats_reader(self):
if self.stats_reader is None:
self.stats_reader = AndroidStatsReader()
return self.stats_reader
def prepare_test(self):
self.core.add_artifact_file(self.volta_core.currents_fname)
[self.core.add_artifact_file(fname) for fname in self.volta_core.event_fnames.values()]
def start_test(self):
try:
self.volta_core.start_test()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.info('Failed to start test of Android plugin', exc_info=True)
return 1
def is_test_finished(self):
try:
if hasattr(self.volta_core, 'phone'):
if hasattr(self.volta_core.phone, 'test_performer'):
if not self.volta_core.phone.test_performer:
logger.warning('There is no test performer process on the phone, interrupting test')
return 1
if not self.volta_core.phone.test_performer.is_finished():
logger.debug('Waiting for phone test to finish...')
return -1
else:
return self.volta_core.phone.test_performer.retcode
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Unknown exception of Android plugin. Interrupting test', exc_info=True)
return 1
def end_test(self, retcode):
try:
self.volta_core.end_test()
uploaders = self.core.get_plugins_of_type(DataUploaderPlugin)
for uploader in uploaders:
response = uploader.lp_job.api_client.link_mobile_job(
lp_key=uploader.lp_job.number,
mobile_key=self.volta_core.uploader.jobno
)
logger.info(
'Linked mobile job %s to %s for plugin: %s. Response: %s',
self.volta_core.uploader.jobno, uploader.lp_job.number, uploader.backend_type, response
)
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete end_test of Android plugin', exc_info=True)
retcode = 1
return retcode
def get_info(self):
return AndroidInfo()
def post_process(self, retcode):
try:
self.volta_core.post_process()
# FIXME raise/catch appropriate exception here
except: # noqa: E722
logger.error('Failed to complete post_process of Android plugin', exc_info=True)
retcode = 1
return retcode
class AndroidInfo(object):
def <|fim_middle|>(self):
self.address = ''
self.port = 80
self.ammo_file = ''
self.duration = 0
self.loop_count = 1
self.instances = 1
self.rps_schedule = ''
<|fim▁end|> | __init__ |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# __init__.py
# cjktools
#
"""<|fim▁hole|>
__all__ = [
'alternations',
'common',
'enum',
'exceptions',
'kana_table',
'maps',
'scripts',
'smart_cache',
'resources',
]<|fim▁end|> | This package contains various tools for Japanese NLP tasks, although some
may be applicable to any python project. See documentation of each module for
details.
""" |
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls.defaults import patterns, url
urlpatterns = patterns(
'popcorn_gallery.users.views',
url(r'^edit/$', 'edit', name='users_edit'),
url(r'^delete/$', 'delete_profile', name='users_delete'),
url(r'^(?P<username>[\w-]+)/$', 'profile', name='users_profile'),<|fim▁hole|>)<|fim▁end|> | |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
<|fim▁hole|> def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()<|fim▁end|> | |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
<|fim_middle|>
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | """An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other) |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
<|fim_middle|>
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
<|fim_middle|>
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | if obj is None:
return
self.mapping = getattr(obj, "mapping", None) |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
<|fim_middle|>
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
<|fim_middle|>
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other) |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
<|fim_middle|>
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other) |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
<|fim_middle|>
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | """Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
<|fim_middle|>
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping) |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
<|fim_middle|>
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | return 'csr' |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
<|fim_middle|>
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | pass |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
<|fim_middle|>
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | return self.data.mapping |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
<|fim_middle|>
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
<|fim_middle|>
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
<|fim_middle|>
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | """An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs) |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
<|fim_middle|>
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value) |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
<|fim_middle|>
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | self.value = value
self.shape = shape |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
<|fim_middle|>
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | return bool(self.value) |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
<|fim_middle|>
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | return np.full(self.shape, self.value) |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
<|fim_middle|>
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | self.name = name
self.shape = shape
self.orbs = orbs |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
<|fim_middle|>
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | return self.name |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
<|fim_middle|>
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | return self.LazyArray(self.name == other, self.shape) |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
<|fim_middle|>
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | return self.LazyArray(self.name != other, self.shape) |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
<|fim_middle|>
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | return hash(self.name) |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
<|fim_middle|>
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | return np.eye(*self.orbs) |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
<|fim_middle|>
<|fim▁end|> | """String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__() |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
<|fim_middle|>
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | return self.split("|")[0] |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
<|fim_middle|>
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | return super().__eq__(other) or self.first == other |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
<|fim_middle|>
def __hash__(self):
return super().__hash__()
<|fim▁end|> | return super().__ne__(other) and self.first != other |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
<|fim_middle|>
<|fim▁end|> | return super().__hash__() |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
<|fim_middle|>
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | return |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
<|fim_middle|>
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | return super().__eq__(self.mapping[other]) |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
<|fim_middle|>
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
<|fim_middle|>
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | result = np.logical_or(result, super().__eq__(v)) |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
<|fim_middle|>
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | return self._mapped_eq(other) |
<|file_name|>alias.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
<|fim_middle|>
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
<|fim▁end|> | return super().__eq__(other) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.