prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>unassignedbugs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
import urllib2
import urllib
from BeautifulSoup import BeautifulSoup
import smtplib
import ConfigParser
# Retreive user information
config = ConfigParser.ConfigParser()
config.read('config.cfg')
user = config.get('data','user')
password = config.get('data','password')
fromaddr = config.get('data','fromaddr')
toaddr = config.get('data','toaddr')
smtpserver = config.get('data','smtp_server')
login_page='https://bugs.archlinux.org/index.php?do=authenticate'
# Create message
msg = "To: %s \nFrom: %s \nSubject: Bug Mail\n\n" % (toaddr,fromaddr)
msg += 'Unassigned bugs \n\n'
# build opener with HTTPCookieProcessor
o = urllib2.build_opener( urllib2.HTTPCookieProcessor() )
urllib2.install_opener( o )
p = urllib.urlencode( { 'user_name': user, 'password': password, 'remember_login' : 'on',} )
f = o.open(login_page, p)
data = f.read()
# Archlinux
url = "https://bugs.archlinux.org/index.php?string=&project=1&search_name=&type%5B%5D=&sev%5B%5D=&pri%5B%5D=&due%5B%5D=0&reported%5B%5D=&cat%5B%5D=&status%5B%5D=1&percent%5B%5D=&opened=&dev=&closed=&duedatefrom=&duedateto=&changedfrom=&changedto=&openedfrom=&openedto=&closedfrom=&closedto=&do=index"
# Community
url2= "https://bugs.archlinux.org/index.php?string=&project=5&search_name=&type%5B%5D=&sev%5B%5D=&pri%5B%5D=&due%5B%5D=0&reported%5B%5D=&cat%5B%5D=&status%5B%5D=1&percent%5B%5D=&opened=&dev=&closed=&duedatefrom=&duedateto=&changedfrom=&changedto=&openedfrom=&openedto=&closedfrom=&closedto=&do=index"
def parse_bugtrackerpage(url,count=1):
print url
# open bugtracker / parse
page = urllib2.urlopen(url)
soup = BeautifulSoup(page)
data = soup.findAll('td',{'class':'task_id'})
msg = ""
pages = False
# Is there another page with unassigned bugs
if soup.findAll('a',{'id': 'next' }) == []:
<|fim_middle|>
else:
print soup.findAll('a',{'id': 'next'})
count += 1
pages = True
print count
# print all found bugs
for f in data:
title = f.a['title'].replace('Assigned |','')
title = f.a['title'].replace('| 0%','')
msg += '* [https://bugs.archlinux.org/task/%s FS#%s] %s \n' % (f.a.string,f.a.string,title)
if pages == True:
new = "%s&pagenum=%s" % (url,count)
msg += parse_bugtrackerpage(new,count)
return msg
msg += '\n\nArchlinux: \n\n'
msg += parse_bugtrackerpage(url)
msg += '\n\nCommunity: \n\n'
msg += parse_bugtrackerpage(url2)
msg = msg.encode("utf8")
# send mail
server = smtplib.SMTP(smtpserver)
server.sendmail(fromaddr, toaddr,msg)
server.quit()
<|fim▁end|> | page = False |
<|file_name|>unassignedbugs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
import urllib2
import urllib
from BeautifulSoup import BeautifulSoup
import smtplib
import ConfigParser
# Retreive user information
config = ConfigParser.ConfigParser()
config.read('config.cfg')
user = config.get('data','user')
password = config.get('data','password')
fromaddr = config.get('data','fromaddr')
toaddr = config.get('data','toaddr')
smtpserver = config.get('data','smtp_server')
login_page='https://bugs.archlinux.org/index.php?do=authenticate'
# Create message
msg = "To: %s \nFrom: %s \nSubject: Bug Mail\n\n" % (toaddr,fromaddr)
msg += 'Unassigned bugs \n\n'
# build opener with HTTPCookieProcessor
o = urllib2.build_opener( urllib2.HTTPCookieProcessor() )
urllib2.install_opener( o )
p = urllib.urlencode( { 'user_name': user, 'password': password, 'remember_login' : 'on',} )
f = o.open(login_page, p)
data = f.read()
# Archlinux
url = "https://bugs.archlinux.org/index.php?string=&project=1&search_name=&type%5B%5D=&sev%5B%5D=&pri%5B%5D=&due%5B%5D=0&reported%5B%5D=&cat%5B%5D=&status%5B%5D=1&percent%5B%5D=&opened=&dev=&closed=&duedatefrom=&duedateto=&changedfrom=&changedto=&openedfrom=&openedto=&closedfrom=&closedto=&do=index"
# Community
url2= "https://bugs.archlinux.org/index.php?string=&project=5&search_name=&type%5B%5D=&sev%5B%5D=&pri%5B%5D=&due%5B%5D=0&reported%5B%5D=&cat%5B%5D=&status%5B%5D=1&percent%5B%5D=&opened=&dev=&closed=&duedatefrom=&duedateto=&changedfrom=&changedto=&openedfrom=&openedto=&closedfrom=&closedto=&do=index"
def parse_bugtrackerpage(url,count=1):
print url
# open bugtracker / parse
page = urllib2.urlopen(url)
soup = BeautifulSoup(page)
data = soup.findAll('td',{'class':'task_id'})
msg = ""
pages = False
# Is there another page with unassigned bugs
if soup.findAll('a',{'id': 'next' }) == []:
page = False
else:
<|fim_middle|>
print count
# print all found bugs
for f in data:
title = f.a['title'].replace('Assigned |','')
title = f.a['title'].replace('| 0%','')
msg += '* [https://bugs.archlinux.org/task/%s FS#%s] %s \n' % (f.a.string,f.a.string,title)
if pages == True:
new = "%s&pagenum=%s" % (url,count)
msg += parse_bugtrackerpage(new,count)
return msg
msg += '\n\nArchlinux: \n\n'
msg += parse_bugtrackerpage(url)
msg += '\n\nCommunity: \n\n'
msg += parse_bugtrackerpage(url2)
msg = msg.encode("utf8")
# send mail
server = smtplib.SMTP(smtpserver)
server.sendmail(fromaddr, toaddr,msg)
server.quit()
<|fim▁end|> | print soup.findAll('a',{'id': 'next'})
count += 1
pages = True |
<|file_name|>unassignedbugs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
import urllib2
import urllib
from BeautifulSoup import BeautifulSoup
import smtplib
import ConfigParser
# Retreive user information
config = ConfigParser.ConfigParser()
config.read('config.cfg')
user = config.get('data','user')
password = config.get('data','password')
fromaddr = config.get('data','fromaddr')
toaddr = config.get('data','toaddr')
smtpserver = config.get('data','smtp_server')
login_page='https://bugs.archlinux.org/index.php?do=authenticate'
# Create message
msg = "To: %s \nFrom: %s \nSubject: Bug Mail\n\n" % (toaddr,fromaddr)
msg += 'Unassigned bugs \n\n'
# build opener with HTTPCookieProcessor
o = urllib2.build_opener( urllib2.HTTPCookieProcessor() )
urllib2.install_opener( o )
p = urllib.urlencode( { 'user_name': user, 'password': password, 'remember_login' : 'on',} )
f = o.open(login_page, p)
data = f.read()
# Archlinux
url = "https://bugs.archlinux.org/index.php?string=&project=1&search_name=&type%5B%5D=&sev%5B%5D=&pri%5B%5D=&due%5B%5D=0&reported%5B%5D=&cat%5B%5D=&status%5B%5D=1&percent%5B%5D=&opened=&dev=&closed=&duedatefrom=&duedateto=&changedfrom=&changedto=&openedfrom=&openedto=&closedfrom=&closedto=&do=index"
# Community
url2= "https://bugs.archlinux.org/index.php?string=&project=5&search_name=&type%5B%5D=&sev%5B%5D=&pri%5B%5D=&due%5B%5D=0&reported%5B%5D=&cat%5B%5D=&status%5B%5D=1&percent%5B%5D=&opened=&dev=&closed=&duedatefrom=&duedateto=&changedfrom=&changedto=&openedfrom=&openedto=&closedfrom=&closedto=&do=index"
def parse_bugtrackerpage(url,count=1):
print url
# open bugtracker / parse
page = urllib2.urlopen(url)
soup = BeautifulSoup(page)
data = soup.findAll('td',{'class':'task_id'})
msg = ""
pages = False
# Is there another page with unassigned bugs
if soup.findAll('a',{'id': 'next' }) == []:
page = False
else:
print soup.findAll('a',{'id': 'next'})
count += 1
pages = True
print count
# print all found bugs
for f in data:
title = f.a['title'].replace('Assigned |','')
title = f.a['title'].replace('| 0%','')
msg += '* [https://bugs.archlinux.org/task/%s FS#%s] %s \n' % (f.a.string,f.a.string,title)
if pages == True:
<|fim_middle|>
return msg
msg += '\n\nArchlinux: \n\n'
msg += parse_bugtrackerpage(url)
msg += '\n\nCommunity: \n\n'
msg += parse_bugtrackerpage(url2)
msg = msg.encode("utf8")
# send mail
server = smtplib.SMTP(smtpserver)
server.sendmail(fromaddr, toaddr,msg)
server.quit()
<|fim▁end|> | new = "%s&pagenum=%s" % (url,count)
msg += parse_bugtrackerpage(new,count) |
<|file_name|>unassignedbugs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
import urllib2
import urllib
from BeautifulSoup import BeautifulSoup
import smtplib
import ConfigParser
# Retreive user information
config = ConfigParser.ConfigParser()
config.read('config.cfg')
user = config.get('data','user')
password = config.get('data','password')
fromaddr = config.get('data','fromaddr')
toaddr = config.get('data','toaddr')
smtpserver = config.get('data','smtp_server')
login_page='https://bugs.archlinux.org/index.php?do=authenticate'
# Create message
msg = "To: %s \nFrom: %s \nSubject: Bug Mail\n\n" % (toaddr,fromaddr)
msg += 'Unassigned bugs \n\n'
# build opener with HTTPCookieProcessor
o = urllib2.build_opener( urllib2.HTTPCookieProcessor() )
urllib2.install_opener( o )
p = urllib.urlencode( { 'user_name': user, 'password': password, 'remember_login' : 'on',} )
f = o.open(login_page, p)
data = f.read()
# Archlinux
url = "https://bugs.archlinux.org/index.php?string=&project=1&search_name=&type%5B%5D=&sev%5B%5D=&pri%5B%5D=&due%5B%5D=0&reported%5B%5D=&cat%5B%5D=&status%5B%5D=1&percent%5B%5D=&opened=&dev=&closed=&duedatefrom=&duedateto=&changedfrom=&changedto=&openedfrom=&openedto=&closedfrom=&closedto=&do=index"
# Community
url2= "https://bugs.archlinux.org/index.php?string=&project=5&search_name=&type%5B%5D=&sev%5B%5D=&pri%5B%5D=&due%5B%5D=0&reported%5B%5D=&cat%5B%5D=&status%5B%5D=1&percent%5B%5D=&opened=&dev=&closed=&duedatefrom=&duedateto=&changedfrom=&changedto=&openedfrom=&openedto=&closedfrom=&closedto=&do=index"
def <|fim_middle|>(url,count=1):
print url
# open bugtracker / parse
page = urllib2.urlopen(url)
soup = BeautifulSoup(page)
data = soup.findAll('td',{'class':'task_id'})
msg = ""
pages = False
# Is there another page with unassigned bugs
if soup.findAll('a',{'id': 'next' }) == []:
page = False
else:
print soup.findAll('a',{'id': 'next'})
count += 1
pages = True
print count
# print all found bugs
for f in data:
title = f.a['title'].replace('Assigned |','')
title = f.a['title'].replace('| 0%','')
msg += '* [https://bugs.archlinux.org/task/%s FS#%s] %s \n' % (f.a.string,f.a.string,title)
if pages == True:
new = "%s&pagenum=%s" % (url,count)
msg += parse_bugtrackerpage(new,count)
return msg
msg += '\n\nArchlinux: \n\n'
msg += parse_bugtrackerpage(url)
msg += '\n\nCommunity: \n\n'
msg += parse_bugtrackerpage(url2)
msg = msg.encode("utf8")
# send mail
server = smtplib.SMTP(smtpserver)
server.sendmail(fromaddr, toaddr,msg)
server.quit()
<|fim▁end|> | parse_bugtrackerpage |
<|file_name|>_mod1_0_1_0_0_4.py<|end_file_name|><|fim▁begin|>name1_0_1_0_0_4_0 = None
name1_0_1_0_0_4_1 = None
name1_0_1_0_0_4_2 = None<|fim▁hole|>
name1_0_1_0_0_4_4 = None<|fim▁end|> |
name1_0_1_0_0_4_3 = None |
<|file_name|>message_format_change_test.py<|end_file_name|><|fim▁begin|># Copyright 2015 Confluent Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,<|fim▁hole|>from ducktape.mark import parametrize
from ducktape.utils.util import wait_until
from kafkatest.services.console_consumer import ConsoleConsumer
from kafkatest.services.kafka import KafkaService
from kafkatest.services.verifiable_producer import VerifiableProducer
from kafkatest.services.zookeeper import ZookeeperService
from kafkatest.tests.produce_consume_validate import ProduceConsumeValidateTest
from kafkatest.utils import is_int
from kafkatest.version import LATEST_0_9, LATEST_0_10, TRUNK, KafkaVersion
class MessageFormatChangeTest(ProduceConsumeValidateTest):
def __init__(self, test_context):
super(MessageFormatChangeTest, self).__init__(test_context=test_context)
def setUp(self):
self.topic = "test_topic"
self.zk = ZookeeperService(self.test_context, num_nodes=1)
self.zk.start()
# Producer and consumer
self.producer_throughput = 10000
self.num_producers = 1
self.num_consumers = 1
self.messages_per_producer = 100
def produce_and_consume(self, producer_version, consumer_version, group):
self.producer = VerifiableProducer(self.test_context, self.num_producers, self.kafka,
self.topic,
throughput=self.producer_throughput,
message_validator=is_int,
version=KafkaVersion(producer_version))
self.consumer = ConsoleConsumer(self.test_context, self.num_consumers, self.kafka,
self.topic, new_consumer=False, consumer_timeout_ms=30000,
message_validator=is_int, version=KafkaVersion(consumer_version))
self.consumer.group_id = group
self.run_produce_consume_validate(lambda: wait_until(
lambda: self.producer.each_produced_at_least(self.messages_per_producer) == True,
timeout_sec=120, backoff_sec=1,
err_msg="Producer did not produce all messages in reasonable amount of time"))
@parametrize(producer_version=str(TRUNK), consumer_version=str(TRUNK))
@parametrize(producer_version=str(LATEST_0_9), consumer_version=str(LATEST_0_9))
def test_compatibility(self, producer_version, consumer_version):
""" This tests performs the following checks:
The workload is a mix of 0.9.x and 0.10.x producers and consumers
that produce to and consume from a 0.10.x cluster
1. initially the topic is using message format 0.9.0
2. change the message format version for topic to 0.10.0 on the fly.
3. change the message format version for topic back to 0.9.0 on the fly.
- The producers and consumers should not have any issue.
- Note that for 0.9.x consumers/producers we only do steps 1 and 2
"""
self.kafka = KafkaService(self.test_context, num_nodes=3, zk=self.zk, version=TRUNK, topics={self.topic: {
"partitions": 3,
"replication-factor": 3,
'configs': {"min.insync.replicas": 2}}})
self.kafka.start()
self.logger.info("First format change to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group1")
self.logger.info("Second format change to 0.10.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_10))
self.produce_and_consume(producer_version, consumer_version, "group2")
if producer_version == str(TRUNK) and consumer_version == str(TRUNK):
self.logger.info("Third format change back to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group3")<|fim▁end|> | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
|
<|file_name|>message_format_change_test.py<|end_file_name|><|fim▁begin|># Copyright 2015 Confluent Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ducktape.mark import parametrize
from ducktape.utils.util import wait_until
from kafkatest.services.console_consumer import ConsoleConsumer
from kafkatest.services.kafka import KafkaService
from kafkatest.services.verifiable_producer import VerifiableProducer
from kafkatest.services.zookeeper import ZookeeperService
from kafkatest.tests.produce_consume_validate import ProduceConsumeValidateTest
from kafkatest.utils import is_int
from kafkatest.version import LATEST_0_9, LATEST_0_10, TRUNK, KafkaVersion
class MessageFormatChangeTest(ProduceConsumeValidateTest):
<|fim_middle|>
<|fim▁end|> | def __init__(self, test_context):
super(MessageFormatChangeTest, self).__init__(test_context=test_context)
def setUp(self):
self.topic = "test_topic"
self.zk = ZookeeperService(self.test_context, num_nodes=1)
self.zk.start()
# Producer and consumer
self.producer_throughput = 10000
self.num_producers = 1
self.num_consumers = 1
self.messages_per_producer = 100
def produce_and_consume(self, producer_version, consumer_version, group):
self.producer = VerifiableProducer(self.test_context, self.num_producers, self.kafka,
self.topic,
throughput=self.producer_throughput,
message_validator=is_int,
version=KafkaVersion(producer_version))
self.consumer = ConsoleConsumer(self.test_context, self.num_consumers, self.kafka,
self.topic, new_consumer=False, consumer_timeout_ms=30000,
message_validator=is_int, version=KafkaVersion(consumer_version))
self.consumer.group_id = group
self.run_produce_consume_validate(lambda: wait_until(
lambda: self.producer.each_produced_at_least(self.messages_per_producer) == True,
timeout_sec=120, backoff_sec=1,
err_msg="Producer did not produce all messages in reasonable amount of time"))
@parametrize(producer_version=str(TRUNK), consumer_version=str(TRUNK))
@parametrize(producer_version=str(LATEST_0_9), consumer_version=str(LATEST_0_9))
def test_compatibility(self, producer_version, consumer_version):
""" This tests performs the following checks:
The workload is a mix of 0.9.x and 0.10.x producers and consumers
that produce to and consume from a 0.10.x cluster
1. initially the topic is using message format 0.9.0
2. change the message format version for topic to 0.10.0 on the fly.
3. change the message format version for topic back to 0.9.0 on the fly.
- The producers and consumers should not have any issue.
- Note that for 0.9.x consumers/producers we only do steps 1 and 2
"""
self.kafka = KafkaService(self.test_context, num_nodes=3, zk=self.zk, version=TRUNK, topics={self.topic: {
"partitions": 3,
"replication-factor": 3,
'configs': {"min.insync.replicas": 2}}})
self.kafka.start()
self.logger.info("First format change to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group1")
self.logger.info("Second format change to 0.10.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_10))
self.produce_and_consume(producer_version, consumer_version, "group2")
if producer_version == str(TRUNK) and consumer_version == str(TRUNK):
self.logger.info("Third format change back to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group3") |
<|file_name|>message_format_change_test.py<|end_file_name|><|fim▁begin|># Copyright 2015 Confluent Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ducktape.mark import parametrize
from ducktape.utils.util import wait_until
from kafkatest.services.console_consumer import ConsoleConsumer
from kafkatest.services.kafka import KafkaService
from kafkatest.services.verifiable_producer import VerifiableProducer
from kafkatest.services.zookeeper import ZookeeperService
from kafkatest.tests.produce_consume_validate import ProduceConsumeValidateTest
from kafkatest.utils import is_int
from kafkatest.version import LATEST_0_9, LATEST_0_10, TRUNK, KafkaVersion
class MessageFormatChangeTest(ProduceConsumeValidateTest):
def __init__(self, test_context):
<|fim_middle|>
def setUp(self):
self.topic = "test_topic"
self.zk = ZookeeperService(self.test_context, num_nodes=1)
self.zk.start()
# Producer and consumer
self.producer_throughput = 10000
self.num_producers = 1
self.num_consumers = 1
self.messages_per_producer = 100
def produce_and_consume(self, producer_version, consumer_version, group):
self.producer = VerifiableProducer(self.test_context, self.num_producers, self.kafka,
self.topic,
throughput=self.producer_throughput,
message_validator=is_int,
version=KafkaVersion(producer_version))
self.consumer = ConsoleConsumer(self.test_context, self.num_consumers, self.kafka,
self.topic, new_consumer=False, consumer_timeout_ms=30000,
message_validator=is_int, version=KafkaVersion(consumer_version))
self.consumer.group_id = group
self.run_produce_consume_validate(lambda: wait_until(
lambda: self.producer.each_produced_at_least(self.messages_per_producer) == True,
timeout_sec=120, backoff_sec=1,
err_msg="Producer did not produce all messages in reasonable amount of time"))
@parametrize(producer_version=str(TRUNK), consumer_version=str(TRUNK))
@parametrize(producer_version=str(LATEST_0_9), consumer_version=str(LATEST_0_9))
def test_compatibility(self, producer_version, consumer_version):
""" This tests performs the following checks:
The workload is a mix of 0.9.x and 0.10.x producers and consumers
that produce to and consume from a 0.10.x cluster
1. initially the topic is using message format 0.9.0
2. change the message format version for topic to 0.10.0 on the fly.
3. change the message format version for topic back to 0.9.0 on the fly.
- The producers and consumers should not have any issue.
- Note that for 0.9.x consumers/producers we only do steps 1 and 2
"""
self.kafka = KafkaService(self.test_context, num_nodes=3, zk=self.zk, version=TRUNK, topics={self.topic: {
"partitions": 3,
"replication-factor": 3,
'configs': {"min.insync.replicas": 2}}})
self.kafka.start()
self.logger.info("First format change to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group1")
self.logger.info("Second format change to 0.10.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_10))
self.produce_and_consume(producer_version, consumer_version, "group2")
if producer_version == str(TRUNK) and consumer_version == str(TRUNK):
self.logger.info("Third format change back to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group3")
<|fim▁end|> | super(MessageFormatChangeTest, self).__init__(test_context=test_context) |
<|file_name|>message_format_change_test.py<|end_file_name|><|fim▁begin|># Copyright 2015 Confluent Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ducktape.mark import parametrize
from ducktape.utils.util import wait_until
from kafkatest.services.console_consumer import ConsoleConsumer
from kafkatest.services.kafka import KafkaService
from kafkatest.services.verifiable_producer import VerifiableProducer
from kafkatest.services.zookeeper import ZookeeperService
from kafkatest.tests.produce_consume_validate import ProduceConsumeValidateTest
from kafkatest.utils import is_int
from kafkatest.version import LATEST_0_9, LATEST_0_10, TRUNK, KafkaVersion
class MessageFormatChangeTest(ProduceConsumeValidateTest):
def __init__(self, test_context):
super(MessageFormatChangeTest, self).__init__(test_context=test_context)
def setUp(self):
<|fim_middle|>
def produce_and_consume(self, producer_version, consumer_version, group):
self.producer = VerifiableProducer(self.test_context, self.num_producers, self.kafka,
self.topic,
throughput=self.producer_throughput,
message_validator=is_int,
version=KafkaVersion(producer_version))
self.consumer = ConsoleConsumer(self.test_context, self.num_consumers, self.kafka,
self.topic, new_consumer=False, consumer_timeout_ms=30000,
message_validator=is_int, version=KafkaVersion(consumer_version))
self.consumer.group_id = group
self.run_produce_consume_validate(lambda: wait_until(
lambda: self.producer.each_produced_at_least(self.messages_per_producer) == True,
timeout_sec=120, backoff_sec=1,
err_msg="Producer did not produce all messages in reasonable amount of time"))
@parametrize(producer_version=str(TRUNK), consumer_version=str(TRUNK))
@parametrize(producer_version=str(LATEST_0_9), consumer_version=str(LATEST_0_9))
def test_compatibility(self, producer_version, consumer_version):
""" This tests performs the following checks:
The workload is a mix of 0.9.x and 0.10.x producers and consumers
that produce to and consume from a 0.10.x cluster
1. initially the topic is using message format 0.9.0
2. change the message format version for topic to 0.10.0 on the fly.
3. change the message format version for topic back to 0.9.0 on the fly.
- The producers and consumers should not have any issue.
- Note that for 0.9.x consumers/producers we only do steps 1 and 2
"""
self.kafka = KafkaService(self.test_context, num_nodes=3, zk=self.zk, version=TRUNK, topics={self.topic: {
"partitions": 3,
"replication-factor": 3,
'configs': {"min.insync.replicas": 2}}})
self.kafka.start()
self.logger.info("First format change to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group1")
self.logger.info("Second format change to 0.10.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_10))
self.produce_and_consume(producer_version, consumer_version, "group2")
if producer_version == str(TRUNK) and consumer_version == str(TRUNK):
self.logger.info("Third format change back to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group3")
<|fim▁end|> | self.topic = "test_topic"
self.zk = ZookeeperService(self.test_context, num_nodes=1)
self.zk.start()
# Producer and consumer
self.producer_throughput = 10000
self.num_producers = 1
self.num_consumers = 1
self.messages_per_producer = 100 |
<|file_name|>message_format_change_test.py<|end_file_name|><|fim▁begin|># Copyright 2015 Confluent Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ducktape.mark import parametrize
from ducktape.utils.util import wait_until
from kafkatest.services.console_consumer import ConsoleConsumer
from kafkatest.services.kafka import KafkaService
from kafkatest.services.verifiable_producer import VerifiableProducer
from kafkatest.services.zookeeper import ZookeeperService
from kafkatest.tests.produce_consume_validate import ProduceConsumeValidateTest
from kafkatest.utils import is_int
from kafkatest.version import LATEST_0_9, LATEST_0_10, TRUNK, KafkaVersion
class MessageFormatChangeTest(ProduceConsumeValidateTest):
def __init__(self, test_context):
super(MessageFormatChangeTest, self).__init__(test_context=test_context)
def setUp(self):
self.topic = "test_topic"
self.zk = ZookeeperService(self.test_context, num_nodes=1)
self.zk.start()
# Producer and consumer
self.producer_throughput = 10000
self.num_producers = 1
self.num_consumers = 1
self.messages_per_producer = 100
def produce_and_consume(self, producer_version, consumer_version, group):
<|fim_middle|>
@parametrize(producer_version=str(TRUNK), consumer_version=str(TRUNK))
@parametrize(producer_version=str(LATEST_0_9), consumer_version=str(LATEST_0_9))
def test_compatibility(self, producer_version, consumer_version):
""" This tests performs the following checks:
The workload is a mix of 0.9.x and 0.10.x producers and consumers
that produce to and consume from a 0.10.x cluster
1. initially the topic is using message format 0.9.0
2. change the message format version for topic to 0.10.0 on the fly.
3. change the message format version for topic back to 0.9.0 on the fly.
- The producers and consumers should not have any issue.
- Note that for 0.9.x consumers/producers we only do steps 1 and 2
"""
self.kafka = KafkaService(self.test_context, num_nodes=3, zk=self.zk, version=TRUNK, topics={self.topic: {
"partitions": 3,
"replication-factor": 3,
'configs': {"min.insync.replicas": 2}}})
self.kafka.start()
self.logger.info("First format change to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group1")
self.logger.info("Second format change to 0.10.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_10))
self.produce_and_consume(producer_version, consumer_version, "group2")
if producer_version == str(TRUNK) and consumer_version == str(TRUNK):
self.logger.info("Third format change back to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group3")
<|fim▁end|> | self.producer = VerifiableProducer(self.test_context, self.num_producers, self.kafka,
self.topic,
throughput=self.producer_throughput,
message_validator=is_int,
version=KafkaVersion(producer_version))
self.consumer = ConsoleConsumer(self.test_context, self.num_consumers, self.kafka,
self.topic, new_consumer=False, consumer_timeout_ms=30000,
message_validator=is_int, version=KafkaVersion(consumer_version))
self.consumer.group_id = group
self.run_produce_consume_validate(lambda: wait_until(
lambda: self.producer.each_produced_at_least(self.messages_per_producer) == True,
timeout_sec=120, backoff_sec=1,
err_msg="Producer did not produce all messages in reasonable amount of time")) |
<|file_name|>message_format_change_test.py<|end_file_name|><|fim▁begin|># Copyright 2015 Confluent Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ducktape.mark import parametrize
from ducktape.utils.util import wait_until
from kafkatest.services.console_consumer import ConsoleConsumer
from kafkatest.services.kafka import KafkaService
from kafkatest.services.verifiable_producer import VerifiableProducer
from kafkatest.services.zookeeper import ZookeeperService
from kafkatest.tests.produce_consume_validate import ProduceConsumeValidateTest
from kafkatest.utils import is_int
from kafkatest.version import LATEST_0_9, LATEST_0_10, TRUNK, KafkaVersion
class MessageFormatChangeTest(ProduceConsumeValidateTest):
def __init__(self, test_context):
super(MessageFormatChangeTest, self).__init__(test_context=test_context)
def setUp(self):
self.topic = "test_topic"
self.zk = ZookeeperService(self.test_context, num_nodes=1)
self.zk.start()
# Producer and consumer
self.producer_throughput = 10000
self.num_producers = 1
self.num_consumers = 1
self.messages_per_producer = 100
def produce_and_consume(self, producer_version, consumer_version, group):
self.producer = VerifiableProducer(self.test_context, self.num_producers, self.kafka,
self.topic,
throughput=self.producer_throughput,
message_validator=is_int,
version=KafkaVersion(producer_version))
self.consumer = ConsoleConsumer(self.test_context, self.num_consumers, self.kafka,
self.topic, new_consumer=False, consumer_timeout_ms=30000,
message_validator=is_int, version=KafkaVersion(consumer_version))
self.consumer.group_id = group
self.run_produce_consume_validate(lambda: wait_until(
lambda: self.producer.each_produced_at_least(self.messages_per_producer) == True,
timeout_sec=120, backoff_sec=1,
err_msg="Producer did not produce all messages in reasonable amount of time"))
@parametrize(producer_version=str(TRUNK), consumer_version=str(TRUNK))
@parametrize(producer_version=str(LATEST_0_9), consumer_version=str(LATEST_0_9))
def test_compatibility(self, producer_version, consumer_version):
<|fim_middle|>
<|fim▁end|> | """ This tests performs the following checks:
The workload is a mix of 0.9.x and 0.10.x producers and consumers
that produce to and consume from a 0.10.x cluster
1. initially the topic is using message format 0.9.0
2. change the message format version for topic to 0.10.0 on the fly.
3. change the message format version for topic back to 0.9.0 on the fly.
- The producers and consumers should not have any issue.
- Note that for 0.9.x consumers/producers we only do steps 1 and 2
"""
self.kafka = KafkaService(self.test_context, num_nodes=3, zk=self.zk, version=TRUNK, topics={self.topic: {
"partitions": 3,
"replication-factor": 3,
'configs': {"min.insync.replicas": 2}}})
self.kafka.start()
self.logger.info("First format change to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group1")
self.logger.info("Second format change to 0.10.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_10))
self.produce_and_consume(producer_version, consumer_version, "group2")
if producer_version == str(TRUNK) and consumer_version == str(TRUNK):
self.logger.info("Third format change back to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group3") |
<|file_name|>message_format_change_test.py<|end_file_name|><|fim▁begin|># Copyright 2015 Confluent Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ducktape.mark import parametrize
from ducktape.utils.util import wait_until
from kafkatest.services.console_consumer import ConsoleConsumer
from kafkatest.services.kafka import KafkaService
from kafkatest.services.verifiable_producer import VerifiableProducer
from kafkatest.services.zookeeper import ZookeeperService
from kafkatest.tests.produce_consume_validate import ProduceConsumeValidateTest
from kafkatest.utils import is_int
from kafkatest.version import LATEST_0_9, LATEST_0_10, TRUNK, KafkaVersion
class MessageFormatChangeTest(ProduceConsumeValidateTest):
def __init__(self, test_context):
super(MessageFormatChangeTest, self).__init__(test_context=test_context)
def setUp(self):
self.topic = "test_topic"
self.zk = ZookeeperService(self.test_context, num_nodes=1)
self.zk.start()
# Producer and consumer
self.producer_throughput = 10000
self.num_producers = 1
self.num_consumers = 1
self.messages_per_producer = 100
def produce_and_consume(self, producer_version, consumer_version, group):
self.producer = VerifiableProducer(self.test_context, self.num_producers, self.kafka,
self.topic,
throughput=self.producer_throughput,
message_validator=is_int,
version=KafkaVersion(producer_version))
self.consumer = ConsoleConsumer(self.test_context, self.num_consumers, self.kafka,
self.topic, new_consumer=False, consumer_timeout_ms=30000,
message_validator=is_int, version=KafkaVersion(consumer_version))
self.consumer.group_id = group
self.run_produce_consume_validate(lambda: wait_until(
lambda: self.producer.each_produced_at_least(self.messages_per_producer) == True,
timeout_sec=120, backoff_sec=1,
err_msg="Producer did not produce all messages in reasonable amount of time"))
@parametrize(producer_version=str(TRUNK), consumer_version=str(TRUNK))
@parametrize(producer_version=str(LATEST_0_9), consumer_version=str(LATEST_0_9))
def test_compatibility(self, producer_version, consumer_version):
""" This tests performs the following checks:
The workload is a mix of 0.9.x and 0.10.x producers and consumers
that produce to and consume from a 0.10.x cluster
1. initially the topic is using message format 0.9.0
2. change the message format version for topic to 0.10.0 on the fly.
3. change the message format version for topic back to 0.9.0 on the fly.
- The producers and consumers should not have any issue.
- Note that for 0.9.x consumers/producers we only do steps 1 and 2
"""
self.kafka = KafkaService(self.test_context, num_nodes=3, zk=self.zk, version=TRUNK, topics={self.topic: {
"partitions": 3,
"replication-factor": 3,
'configs': {"min.insync.replicas": 2}}})
self.kafka.start()
self.logger.info("First format change to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group1")
self.logger.info("Second format change to 0.10.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_10))
self.produce_and_consume(producer_version, consumer_version, "group2")
if producer_version == str(TRUNK) and consumer_version == str(TRUNK):
<|fim_middle|>
<|fim▁end|> | self.logger.info("Third format change back to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group3") |
<|file_name|>message_format_change_test.py<|end_file_name|><|fim▁begin|># Copyright 2015 Confluent Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ducktape.mark import parametrize
from ducktape.utils.util import wait_until
from kafkatest.services.console_consumer import ConsoleConsumer
from kafkatest.services.kafka import KafkaService
from kafkatest.services.verifiable_producer import VerifiableProducer
from kafkatest.services.zookeeper import ZookeeperService
from kafkatest.tests.produce_consume_validate import ProduceConsumeValidateTest
from kafkatest.utils import is_int
from kafkatest.version import LATEST_0_9, LATEST_0_10, TRUNK, KafkaVersion
class MessageFormatChangeTest(ProduceConsumeValidateTest):
def <|fim_middle|>(self, test_context):
super(MessageFormatChangeTest, self).__init__(test_context=test_context)
def setUp(self):
self.topic = "test_topic"
self.zk = ZookeeperService(self.test_context, num_nodes=1)
self.zk.start()
# Producer and consumer
self.producer_throughput = 10000
self.num_producers = 1
self.num_consumers = 1
self.messages_per_producer = 100
def produce_and_consume(self, producer_version, consumer_version, group):
self.producer = VerifiableProducer(self.test_context, self.num_producers, self.kafka,
self.topic,
throughput=self.producer_throughput,
message_validator=is_int,
version=KafkaVersion(producer_version))
self.consumer = ConsoleConsumer(self.test_context, self.num_consumers, self.kafka,
self.topic, new_consumer=False, consumer_timeout_ms=30000,
message_validator=is_int, version=KafkaVersion(consumer_version))
self.consumer.group_id = group
self.run_produce_consume_validate(lambda: wait_until(
lambda: self.producer.each_produced_at_least(self.messages_per_producer) == True,
timeout_sec=120, backoff_sec=1,
err_msg="Producer did not produce all messages in reasonable amount of time"))
@parametrize(producer_version=str(TRUNK), consumer_version=str(TRUNK))
@parametrize(producer_version=str(LATEST_0_9), consumer_version=str(LATEST_0_9))
def test_compatibility(self, producer_version, consumer_version):
""" This tests performs the following checks:
The workload is a mix of 0.9.x and 0.10.x producers and consumers
that produce to and consume from a 0.10.x cluster
1. initially the topic is using message format 0.9.0
2. change the message format version for topic to 0.10.0 on the fly.
3. change the message format version for topic back to 0.9.0 on the fly.
- The producers and consumers should not have any issue.
- Note that for 0.9.x consumers/producers we only do steps 1 and 2
"""
self.kafka = KafkaService(self.test_context, num_nodes=3, zk=self.zk, version=TRUNK, topics={self.topic: {
"partitions": 3,
"replication-factor": 3,
'configs': {"min.insync.replicas": 2}}})
self.kafka.start()
self.logger.info("First format change to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group1")
self.logger.info("Second format change to 0.10.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_10))
self.produce_and_consume(producer_version, consumer_version, "group2")
if producer_version == str(TRUNK) and consumer_version == str(TRUNK):
self.logger.info("Third format change back to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group3")
<|fim▁end|> | __init__ |
<|file_name|>message_format_change_test.py<|end_file_name|><|fim▁begin|># Copyright 2015 Confluent Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ducktape.mark import parametrize
from ducktape.utils.util import wait_until
from kafkatest.services.console_consumer import ConsoleConsumer
from kafkatest.services.kafka import KafkaService
from kafkatest.services.verifiable_producer import VerifiableProducer
from kafkatest.services.zookeeper import ZookeeperService
from kafkatest.tests.produce_consume_validate import ProduceConsumeValidateTest
from kafkatest.utils import is_int
from kafkatest.version import LATEST_0_9, LATEST_0_10, TRUNK, KafkaVersion
class MessageFormatChangeTest(ProduceConsumeValidateTest):
def __init__(self, test_context):
super(MessageFormatChangeTest, self).__init__(test_context=test_context)
def <|fim_middle|>(self):
self.topic = "test_topic"
self.zk = ZookeeperService(self.test_context, num_nodes=1)
self.zk.start()
# Producer and consumer
self.producer_throughput = 10000
self.num_producers = 1
self.num_consumers = 1
self.messages_per_producer = 100
def produce_and_consume(self, producer_version, consumer_version, group):
self.producer = VerifiableProducer(self.test_context, self.num_producers, self.kafka,
self.topic,
throughput=self.producer_throughput,
message_validator=is_int,
version=KafkaVersion(producer_version))
self.consumer = ConsoleConsumer(self.test_context, self.num_consumers, self.kafka,
self.topic, new_consumer=False, consumer_timeout_ms=30000,
message_validator=is_int, version=KafkaVersion(consumer_version))
self.consumer.group_id = group
self.run_produce_consume_validate(lambda: wait_until(
lambda: self.producer.each_produced_at_least(self.messages_per_producer) == True,
timeout_sec=120, backoff_sec=1,
err_msg="Producer did not produce all messages in reasonable amount of time"))
@parametrize(producer_version=str(TRUNK), consumer_version=str(TRUNK))
@parametrize(producer_version=str(LATEST_0_9), consumer_version=str(LATEST_0_9))
def test_compatibility(self, producer_version, consumer_version):
""" This tests performs the following checks:
The workload is a mix of 0.9.x and 0.10.x producers and consumers
that produce to and consume from a 0.10.x cluster
1. initially the topic is using message format 0.9.0
2. change the message format version for topic to 0.10.0 on the fly.
3. change the message format version for topic back to 0.9.0 on the fly.
- The producers and consumers should not have any issue.
- Note that for 0.9.x consumers/producers we only do steps 1 and 2
"""
self.kafka = KafkaService(self.test_context, num_nodes=3, zk=self.zk, version=TRUNK, topics={self.topic: {
"partitions": 3,
"replication-factor": 3,
'configs': {"min.insync.replicas": 2}}})
self.kafka.start()
self.logger.info("First format change to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group1")
self.logger.info("Second format change to 0.10.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_10))
self.produce_and_consume(producer_version, consumer_version, "group2")
if producer_version == str(TRUNK) and consumer_version == str(TRUNK):
self.logger.info("Third format change back to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group3")
<|fim▁end|> | setUp |
<|file_name|>message_format_change_test.py<|end_file_name|><|fim▁begin|># Copyright 2015 Confluent Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ducktape.mark import parametrize
from ducktape.utils.util import wait_until
from kafkatest.services.console_consumer import ConsoleConsumer
from kafkatest.services.kafka import KafkaService
from kafkatest.services.verifiable_producer import VerifiableProducer
from kafkatest.services.zookeeper import ZookeeperService
from kafkatest.tests.produce_consume_validate import ProduceConsumeValidateTest
from kafkatest.utils import is_int
from kafkatest.version import LATEST_0_9, LATEST_0_10, TRUNK, KafkaVersion
class MessageFormatChangeTest(ProduceConsumeValidateTest):
def __init__(self, test_context):
super(MessageFormatChangeTest, self).__init__(test_context=test_context)
def setUp(self):
self.topic = "test_topic"
self.zk = ZookeeperService(self.test_context, num_nodes=1)
self.zk.start()
# Producer and consumer
self.producer_throughput = 10000
self.num_producers = 1
self.num_consumers = 1
self.messages_per_producer = 100
def <|fim_middle|>(self, producer_version, consumer_version, group):
self.producer = VerifiableProducer(self.test_context, self.num_producers, self.kafka,
self.topic,
throughput=self.producer_throughput,
message_validator=is_int,
version=KafkaVersion(producer_version))
self.consumer = ConsoleConsumer(self.test_context, self.num_consumers, self.kafka,
self.topic, new_consumer=False, consumer_timeout_ms=30000,
message_validator=is_int, version=KafkaVersion(consumer_version))
self.consumer.group_id = group
self.run_produce_consume_validate(lambda: wait_until(
lambda: self.producer.each_produced_at_least(self.messages_per_producer) == True,
timeout_sec=120, backoff_sec=1,
err_msg="Producer did not produce all messages in reasonable amount of time"))
@parametrize(producer_version=str(TRUNK), consumer_version=str(TRUNK))
@parametrize(producer_version=str(LATEST_0_9), consumer_version=str(LATEST_0_9))
def test_compatibility(self, producer_version, consumer_version):
""" This tests performs the following checks:
The workload is a mix of 0.9.x and 0.10.x producers and consumers
that produce to and consume from a 0.10.x cluster
1. initially the topic is using message format 0.9.0
2. change the message format version for topic to 0.10.0 on the fly.
3. change the message format version for topic back to 0.9.0 on the fly.
- The producers and consumers should not have any issue.
- Note that for 0.9.x consumers/producers we only do steps 1 and 2
"""
self.kafka = KafkaService(self.test_context, num_nodes=3, zk=self.zk, version=TRUNK, topics={self.topic: {
"partitions": 3,
"replication-factor": 3,
'configs': {"min.insync.replicas": 2}}})
self.kafka.start()
self.logger.info("First format change to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group1")
self.logger.info("Second format change to 0.10.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_10))
self.produce_and_consume(producer_version, consumer_version, "group2")
if producer_version == str(TRUNK) and consumer_version == str(TRUNK):
self.logger.info("Third format change back to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group3")
<|fim▁end|> | produce_and_consume |
<|file_name|>message_format_change_test.py<|end_file_name|><|fim▁begin|># Copyright 2015 Confluent Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ducktape.mark import parametrize
from ducktape.utils.util import wait_until
from kafkatest.services.console_consumer import ConsoleConsumer
from kafkatest.services.kafka import KafkaService
from kafkatest.services.verifiable_producer import VerifiableProducer
from kafkatest.services.zookeeper import ZookeeperService
from kafkatest.tests.produce_consume_validate import ProduceConsumeValidateTest
from kafkatest.utils import is_int
from kafkatest.version import LATEST_0_9, LATEST_0_10, TRUNK, KafkaVersion
class MessageFormatChangeTest(ProduceConsumeValidateTest):
def __init__(self, test_context):
super(MessageFormatChangeTest, self).__init__(test_context=test_context)
def setUp(self):
self.topic = "test_topic"
self.zk = ZookeeperService(self.test_context, num_nodes=1)
self.zk.start()
# Producer and consumer
self.producer_throughput = 10000
self.num_producers = 1
self.num_consumers = 1
self.messages_per_producer = 100
def produce_and_consume(self, producer_version, consumer_version, group):
self.producer = VerifiableProducer(self.test_context, self.num_producers, self.kafka,
self.topic,
throughput=self.producer_throughput,
message_validator=is_int,
version=KafkaVersion(producer_version))
self.consumer = ConsoleConsumer(self.test_context, self.num_consumers, self.kafka,
self.topic, new_consumer=False, consumer_timeout_ms=30000,
message_validator=is_int, version=KafkaVersion(consumer_version))
self.consumer.group_id = group
self.run_produce_consume_validate(lambda: wait_until(
lambda: self.producer.each_produced_at_least(self.messages_per_producer) == True,
timeout_sec=120, backoff_sec=1,
err_msg="Producer did not produce all messages in reasonable amount of time"))
@parametrize(producer_version=str(TRUNK), consumer_version=str(TRUNK))
@parametrize(producer_version=str(LATEST_0_9), consumer_version=str(LATEST_0_9))
def <|fim_middle|>(self, producer_version, consumer_version):
""" This tests performs the following checks:
The workload is a mix of 0.9.x and 0.10.x producers and consumers
that produce to and consume from a 0.10.x cluster
1. initially the topic is using message format 0.9.0
2. change the message format version for topic to 0.10.0 on the fly.
3. change the message format version for topic back to 0.9.0 on the fly.
- The producers and consumers should not have any issue.
- Note that for 0.9.x consumers/producers we only do steps 1 and 2
"""
self.kafka = KafkaService(self.test_context, num_nodes=3, zk=self.zk, version=TRUNK, topics={self.topic: {
"partitions": 3,
"replication-factor": 3,
'configs': {"min.insync.replicas": 2}}})
self.kafka.start()
self.logger.info("First format change to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group1")
self.logger.info("Second format change to 0.10.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_10))
self.produce_and_consume(producer_version, consumer_version, "group2")
if producer_version == str(TRUNK) and consumer_version == str(TRUNK):
self.logger.info("Third format change back to 0.9.0")
self.kafka.alter_message_format(self.topic, str(LATEST_0_9))
self.produce_and_consume(producer_version, consumer_version, "group3")
<|fim▁end|> | test_compatibility |
<|file_name|>schemamigration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mptt',
'cms',
'menus',
'djangocms_inherit',
'south',<|fim▁hole|> 'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
TEMPLATE_CONTEXT_PROCESSORS = [
'django.core.context_processors.auth',
'django.core.context_processors.i18n',
'django.core.context_processors.request',
'django.core.context_processors.media',
'django.core.context_processors.static',
'cms.context_processors.media',
'sekizai.context_processors.sekizai',
]
ROOT_URLCONF = 'cms.urls'
def schemamigration():
# turn ``schemamigration.py --initial`` into
# ``manage.py schemamigration cmsplugin_disqus --initial`` and setup the
# enviroment
from django.conf import settings
from django.core.management import ManagementUtility
settings.configure(
INSTALLED_APPS=INSTALLED_APPS,
ROOT_URLCONF=ROOT_URLCONF,
DATABASES=DATABASES,
TEMPLATE_CONTEXT_PROCESSORS=TEMPLATE_CONTEXT_PROCESSORS
)
argv = list(sys.argv)
argv.insert(1, 'schemamigration')
argv.insert(2, 'djangocms_inherit')
utility = ManagementUtility(argv)
utility.execute()
if __name__ == "__main__":
schemamigration()<|fim▁end|> | ]
DATABASES = { |
<|file_name|>schemamigration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mptt',
'cms',
'menus',
'djangocms_inherit',
'south',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
TEMPLATE_CONTEXT_PROCESSORS = [
'django.core.context_processors.auth',
'django.core.context_processors.i18n',
'django.core.context_processors.request',
'django.core.context_processors.media',
'django.core.context_processors.static',
'cms.context_processors.media',
'sekizai.context_processors.sekizai',
]
ROOT_URLCONF = 'cms.urls'
def schemamigration():
# turn ``schemamigration.py --initial`` into
# ``manage.py schemamigration cmsplugin_disqus --initial`` and setup the
# enviroment
<|fim_middle|>
if __name__ == "__main__":
schemamigration()
<|fim▁end|> | from django.conf import settings
from django.core.management import ManagementUtility
settings.configure(
INSTALLED_APPS=INSTALLED_APPS,
ROOT_URLCONF=ROOT_URLCONF,
DATABASES=DATABASES,
TEMPLATE_CONTEXT_PROCESSORS=TEMPLATE_CONTEXT_PROCESSORS
)
argv = list(sys.argv)
argv.insert(1, 'schemamigration')
argv.insert(2, 'djangocms_inherit')
utility = ManagementUtility(argv)
utility.execute() |
<|file_name|>schemamigration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mptt',
'cms',
'menus',
'djangocms_inherit',
'south',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
TEMPLATE_CONTEXT_PROCESSORS = [
'django.core.context_processors.auth',
'django.core.context_processors.i18n',
'django.core.context_processors.request',
'django.core.context_processors.media',
'django.core.context_processors.static',
'cms.context_processors.media',
'sekizai.context_processors.sekizai',
]
ROOT_URLCONF = 'cms.urls'
def schemamigration():
# turn ``schemamigration.py --initial`` into
# ``manage.py schemamigration cmsplugin_disqus --initial`` and setup the
# enviroment
from django.conf import settings
from django.core.management import ManagementUtility
settings.configure(
INSTALLED_APPS=INSTALLED_APPS,
ROOT_URLCONF=ROOT_URLCONF,
DATABASES=DATABASES,
TEMPLATE_CONTEXT_PROCESSORS=TEMPLATE_CONTEXT_PROCESSORS
)
argv = list(sys.argv)
argv.insert(1, 'schemamigration')
argv.insert(2, 'djangocms_inherit')
utility = ManagementUtility(argv)
utility.execute()
if __name__ == "__main__":
<|fim_middle|>
<|fim▁end|> | schemamigration() |
<|file_name|>schemamigration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mptt',
'cms',
'menus',
'djangocms_inherit',
'south',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
TEMPLATE_CONTEXT_PROCESSORS = [
'django.core.context_processors.auth',
'django.core.context_processors.i18n',
'django.core.context_processors.request',
'django.core.context_processors.media',
'django.core.context_processors.static',
'cms.context_processors.media',
'sekizai.context_processors.sekizai',
]
ROOT_URLCONF = 'cms.urls'
def <|fim_middle|>():
# turn ``schemamigration.py --initial`` into
# ``manage.py schemamigration cmsplugin_disqus --initial`` and setup the
# enviroment
from django.conf import settings
from django.core.management import ManagementUtility
settings.configure(
INSTALLED_APPS=INSTALLED_APPS,
ROOT_URLCONF=ROOT_URLCONF,
DATABASES=DATABASES,
TEMPLATE_CONTEXT_PROCESSORS=TEMPLATE_CONTEXT_PROCESSORS
)
argv = list(sys.argv)
argv.insert(1, 'schemamigration')
argv.insert(2, 'djangocms_inherit')
utility = ManagementUtility(argv)
utility.execute()
if __name__ == "__main__":
schemamigration()
<|fim▁end|> | schemamigration |
<|file_name|>sbcsgroupprober.py<|end_file_name|><|fim▁begin|><|fim▁hole|># The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
# Shy Shalom - original C code
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
import constants, sys
from charsetgroupprober import CharSetGroupProber
from sbcharsetprober import SingleByteCharSetProber
from langcyrillicmodel import Win1251CyrillicModel, Koi8rModel, Latin5CyrillicModel, MacCyrillicModel, Ibm866Model, Ibm855Model
from langgreekmodel import Latin7GreekModel, Win1253GreekModel
from langbulgarianmodel import Latin5BulgarianModel, Win1251BulgarianModel
from langhungarianmodel import Latin2HungarianModel, Win1250HungarianModel
from langthaimodel import TIS620ThaiModel
from langhebrewmodel import Win1255HebrewModel
from hebrewprober import HebrewProber
class SBCSGroupProber(CharSetGroupProber):
def __init__(self):
CharSetGroupProber.__init__(self)
self._mProbers = [ \
SingleByteCharSetProber(Win1251CyrillicModel),
SingleByteCharSetProber(Koi8rModel),
SingleByteCharSetProber(Latin5CyrillicModel),
SingleByteCharSetProber(MacCyrillicModel),
SingleByteCharSetProber(Ibm866Model),
SingleByteCharSetProber(Ibm855Model),
SingleByteCharSetProber(Latin7GreekModel),
SingleByteCharSetProber(Win1253GreekModel),
SingleByteCharSetProber(Latin5BulgarianModel),
SingleByteCharSetProber(Win1251BulgarianModel),
SingleByteCharSetProber(Latin2HungarianModel),
SingleByteCharSetProber(Win1250HungarianModel),
SingleByteCharSetProber(TIS620ThaiModel),
]
hebrewProber = HebrewProber()
logicalHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, constants.False, hebrewProber)
visualHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, constants.True, hebrewProber)
hebrewProber.set_model_probers(logicalHebrewProber, visualHebrewProber)
self._mProbers.extend([hebrewProber, logicalHebrewProber, visualHebrewProber])
self.reset()<|fim▁end|> | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Universal charset detector code.
# |
<|file_name|>sbcsgroupprober.py<|end_file_name|><|fim▁begin|>######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Universal charset detector code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
# Shy Shalom - original C code
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
import constants, sys
from charsetgroupprober import CharSetGroupProber
from sbcharsetprober import SingleByteCharSetProber
from langcyrillicmodel import Win1251CyrillicModel, Koi8rModel, Latin5CyrillicModel, MacCyrillicModel, Ibm866Model, Ibm855Model
from langgreekmodel import Latin7GreekModel, Win1253GreekModel
from langbulgarianmodel import Latin5BulgarianModel, Win1251BulgarianModel
from langhungarianmodel import Latin2HungarianModel, Win1250HungarianModel
from langthaimodel import TIS620ThaiModel
from langhebrewmodel import Win1255HebrewModel
from hebrewprober import HebrewProber
class SBCSGroupProber(CharSetGroupProber):
<|fim_middle|>
<|fim▁end|> | def __init__(self):
CharSetGroupProber.__init__(self)
self._mProbers = [ \
SingleByteCharSetProber(Win1251CyrillicModel),
SingleByteCharSetProber(Koi8rModel),
SingleByteCharSetProber(Latin5CyrillicModel),
SingleByteCharSetProber(MacCyrillicModel),
SingleByteCharSetProber(Ibm866Model),
SingleByteCharSetProber(Ibm855Model),
SingleByteCharSetProber(Latin7GreekModel),
SingleByteCharSetProber(Win1253GreekModel),
SingleByteCharSetProber(Latin5BulgarianModel),
SingleByteCharSetProber(Win1251BulgarianModel),
SingleByteCharSetProber(Latin2HungarianModel),
SingleByteCharSetProber(Win1250HungarianModel),
SingleByteCharSetProber(TIS620ThaiModel),
]
hebrewProber = HebrewProber()
logicalHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, constants.False, hebrewProber)
visualHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, constants.True, hebrewProber)
hebrewProber.set_model_probers(logicalHebrewProber, visualHebrewProber)
self._mProbers.extend([hebrewProber, logicalHebrewProber, visualHebrewProber])
self.reset() |
<|file_name|>sbcsgroupprober.py<|end_file_name|><|fim▁begin|>######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Universal charset detector code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
# Shy Shalom - original C code
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
import constants, sys
from charsetgroupprober import CharSetGroupProber
from sbcharsetprober import SingleByteCharSetProber
from langcyrillicmodel import Win1251CyrillicModel, Koi8rModel, Latin5CyrillicModel, MacCyrillicModel, Ibm866Model, Ibm855Model
from langgreekmodel import Latin7GreekModel, Win1253GreekModel
from langbulgarianmodel import Latin5BulgarianModel, Win1251BulgarianModel
from langhungarianmodel import Latin2HungarianModel, Win1250HungarianModel
from langthaimodel import TIS620ThaiModel
from langhebrewmodel import Win1255HebrewModel
from hebrewprober import HebrewProber
class SBCSGroupProber(CharSetGroupProber):
def __init__(self):
<|fim_middle|>
<|fim▁end|> | CharSetGroupProber.__init__(self)
self._mProbers = [ \
SingleByteCharSetProber(Win1251CyrillicModel),
SingleByteCharSetProber(Koi8rModel),
SingleByteCharSetProber(Latin5CyrillicModel),
SingleByteCharSetProber(MacCyrillicModel),
SingleByteCharSetProber(Ibm866Model),
SingleByteCharSetProber(Ibm855Model),
SingleByteCharSetProber(Latin7GreekModel),
SingleByteCharSetProber(Win1253GreekModel),
SingleByteCharSetProber(Latin5BulgarianModel),
SingleByteCharSetProber(Win1251BulgarianModel),
SingleByteCharSetProber(Latin2HungarianModel),
SingleByteCharSetProber(Win1250HungarianModel),
SingleByteCharSetProber(TIS620ThaiModel),
]
hebrewProber = HebrewProber()
logicalHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, constants.False, hebrewProber)
visualHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, constants.True, hebrewProber)
hebrewProber.set_model_probers(logicalHebrewProber, visualHebrewProber)
self._mProbers.extend([hebrewProber, logicalHebrewProber, visualHebrewProber])
self.reset() |
<|file_name|>sbcsgroupprober.py<|end_file_name|><|fim▁begin|>######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Universal charset detector code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
# Shy Shalom - original C code
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
import constants, sys
from charsetgroupprober import CharSetGroupProber
from sbcharsetprober import SingleByteCharSetProber
from langcyrillicmodel import Win1251CyrillicModel, Koi8rModel, Latin5CyrillicModel, MacCyrillicModel, Ibm866Model, Ibm855Model
from langgreekmodel import Latin7GreekModel, Win1253GreekModel
from langbulgarianmodel import Latin5BulgarianModel, Win1251BulgarianModel
from langhungarianmodel import Latin2HungarianModel, Win1250HungarianModel
from langthaimodel import TIS620ThaiModel
from langhebrewmodel import Win1255HebrewModel
from hebrewprober import HebrewProber
class SBCSGroupProber(CharSetGroupProber):
def <|fim_middle|>(self):
CharSetGroupProber.__init__(self)
self._mProbers = [ \
SingleByteCharSetProber(Win1251CyrillicModel),
SingleByteCharSetProber(Koi8rModel),
SingleByteCharSetProber(Latin5CyrillicModel),
SingleByteCharSetProber(MacCyrillicModel),
SingleByteCharSetProber(Ibm866Model),
SingleByteCharSetProber(Ibm855Model),
SingleByteCharSetProber(Latin7GreekModel),
SingleByteCharSetProber(Win1253GreekModel),
SingleByteCharSetProber(Latin5BulgarianModel),
SingleByteCharSetProber(Win1251BulgarianModel),
SingleByteCharSetProber(Latin2HungarianModel),
SingleByteCharSetProber(Win1250HungarianModel),
SingleByteCharSetProber(TIS620ThaiModel),
]
hebrewProber = HebrewProber()
logicalHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, constants.False, hebrewProber)
visualHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, constants.True, hebrewProber)
hebrewProber.set_model_probers(logicalHebrewProber, visualHebrewProber)
self._mProbers.extend([hebrewProber, logicalHebrewProber, visualHebrewProber])
self.reset()
<|fim▁end|> | __init__ |
<|file_name|>missing_symbols.py<|end_file_name|><|fim▁begin|>"""
Copyright (c) 2016 Genome Research Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import time
import sys
import json
try:
import urllib.request as request
from urllib.error import HTTPError
except ImportError:
import urllib2 as request
from urllib2 import HTTPError
import pandas
PREV_TIME = time.time()
IS_PYTHON3 = sys.version[0] == "3"
def fix_missing_gene_symbols(de_novos, build='grch37'):
""" adds gene symbols to variants lacking them.
Args:
de_novos: dataframe of de novo variants
build: whether to use the 'grch37' or 'grch38' build (default=GRCh37)
Returns:
pandas Series of HGNC symbols, with additional annotations for many
variants previously lacking a HGNC symbol.
"""
symbols = de_novos["symbol"].copy()
# get the variants with no gene annotation, ensure chrom, start and stop
# positions columns exist
missing = de_novos[symbols == ""].copy()
missing['end'] = missing["pos"] + missing["ref"].str.len() - 1
# find the HGNC symbols (if any) for the variants<|fim▁hole|> symbols[de_novos["symbol"] == ""] = missing
# 360 out of 17000 de novos still lack HGNC symbols. Their consequences are:
#
# consequence count
# ======================== =====
# downstream_gene_variant 17
# intergenic_variant 259
# regulatory_region_variant 63
# upstream_gene_variant 27
#
# In spot checks, these are sufficiently distant from genes that we can't
# add them to the analysis of their nearest gene. We shall analyse these
# per site by giving them mock gene symbols.
missing = de_novos[symbols == ""].copy()
fake = 'fake_symbol.' + missing['chrom'].map(str) + '_' + missing["pos"].map(str)
symbols[symbols == ""] = fake
return symbols
def open_url(url, headers):
""" open url with python libraries
Args:
url:
headers:
Returns:
tuple of http response, http response code, and http headers
"""
req = request.Request(url, headers=headers)
try:
handler = request.urlopen(req)
except HTTPError as e:
handler = e
status_code = handler.getcode()
response = handler.read()
if IS_PYTHON3:
response = response.decode("utf-8")
# parse the headers into a key, value dictionary
headers = dict(zip(map(str.lower, handler.headers.keys()), handler.headers.values()))
return response, status_code, headers
def rate_limit_requests(rate_limit=0.0667):
""" limit ensembl requests to one per 0.067 s
"""
global PREV_TIME
diff = time.time() - PREV_TIME
if diff < rate_limit:
time.sleep(rate_limit - diff)
PREV_TIME = time.time()
def get_gene_id(chrom, start_pos, end_pos, build="grch37", verbose=False, attempts=0):
"""find the hgnc symbol overlapping a variant position
Args:
variant: data frame or list for a variant, containing columns named
"chrom", "start_pos", and "end_pos" for a single variant
build: genome build to find consequences on
verbose: flag indicating whether to print variants as they are checked
Returns:
a character string containing the HGNC symbol.
"""
attempts += 1
if attempts > 5:
raise ValueError("too many attempts, figure out why its failing")
rate_limit_requests()
# define parts of the URL
ext = "overlap/region/human/{0}:{1}-{2}?feature=gene".format(chrom, start_pos, end_pos)
server_dict = {"grch37": "grch37.", "grch38": ""}
base_url = "http://{}rest.ensembl.org".format(server_dict[build])
url = "{0}/{1}".format(base_url, ext)
headers = {"Content-Type" : "application/json"}
if verbose:
print("chr{0}:{1} {2}".format(chrom, start_pos, ext))
response, status_code, requested_headers = open_url(url, headers)
if status_code == 429:
if "retry-after" in requested_headers:
time.sleep(float(requested_headers["retry-after"]))
elif "x-ratelimit-reset" in requested_headers:
time.sleep(int(requested_headers["x-ratelimit-reset"]))
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code in [503, 504]:
time.sleep(30)
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code != 200:
raise ValueError('Invalid Ensembl response: {0}.\nSubmitted '
'URL was: {1}{2}\nheaders: {3}\nresponse: {4}'.format(status_code,
base_url, ext, requested_headers, response))
json_text = json.loads(response)
if len(json_text) > 0:
return json_text[0]["external_name"]
return ""<|fim▁end|> | missing = [ get_gene_id(x["chrom"], x["pos"], x['end'], build=build, verbose=True) for i, x in missing.iterrows() ] |
<|file_name|>missing_symbols.py<|end_file_name|><|fim▁begin|>"""
Copyright (c) 2016 Genome Research Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import time
import sys
import json
try:
import urllib.request as request
from urllib.error import HTTPError
except ImportError:
import urllib2 as request
from urllib2 import HTTPError
import pandas
PREV_TIME = time.time()
IS_PYTHON3 = sys.version[0] == "3"
def fix_missing_gene_symbols(de_novos, build='grch37'):
<|fim_middle|>
def open_url(url, headers):
""" open url with python libraries
Args:
url:
headers:
Returns:
tuple of http response, http response code, and http headers
"""
req = request.Request(url, headers=headers)
try:
handler = request.urlopen(req)
except HTTPError as e:
handler = e
status_code = handler.getcode()
response = handler.read()
if IS_PYTHON3:
response = response.decode("utf-8")
# parse the headers into a key, value dictionary
headers = dict(zip(map(str.lower, handler.headers.keys()), handler.headers.values()))
return response, status_code, headers
def rate_limit_requests(rate_limit=0.0667):
""" limit ensembl requests to one per 0.067 s
"""
global PREV_TIME
diff = time.time() - PREV_TIME
if diff < rate_limit:
time.sleep(rate_limit - diff)
PREV_TIME = time.time()
def get_gene_id(chrom, start_pos, end_pos, build="grch37", verbose=False, attempts=0):
"""find the hgnc symbol overlapping a variant position
Args:
variant: data frame or list for a variant, containing columns named
"chrom", "start_pos", and "end_pos" for a single variant
build: genome build to find consequences on
verbose: flag indicating whether to print variants as they are checked
Returns:
a character string containing the HGNC symbol.
"""
attempts += 1
if attempts > 5:
raise ValueError("too many attempts, figure out why its failing")
rate_limit_requests()
# define parts of the URL
ext = "overlap/region/human/{0}:{1}-{2}?feature=gene".format(chrom, start_pos, end_pos)
server_dict = {"grch37": "grch37.", "grch38": ""}
base_url = "http://{}rest.ensembl.org".format(server_dict[build])
url = "{0}/{1}".format(base_url, ext)
headers = {"Content-Type" : "application/json"}
if verbose:
print("chr{0}:{1} {2}".format(chrom, start_pos, ext))
response, status_code, requested_headers = open_url(url, headers)
if status_code == 429:
if "retry-after" in requested_headers:
time.sleep(float(requested_headers["retry-after"]))
elif "x-ratelimit-reset" in requested_headers:
time.sleep(int(requested_headers["x-ratelimit-reset"]))
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code in [503, 504]:
time.sleep(30)
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code != 200:
raise ValueError('Invalid Ensembl response: {0}.\nSubmitted '
'URL was: {1}{2}\nheaders: {3}\nresponse: {4}'.format(status_code,
base_url, ext, requested_headers, response))
json_text = json.loads(response)
if len(json_text) > 0:
return json_text[0]["external_name"]
return ""
<|fim▁end|> | """ adds gene symbols to variants lacking them.
Args:
de_novos: dataframe of de novo variants
build: whether to use the 'grch37' or 'grch38' build (default=GRCh37)
Returns:
pandas Series of HGNC symbols, with additional annotations for many
variants previously lacking a HGNC symbol.
"""
symbols = de_novos["symbol"].copy()
# get the variants with no gene annotation, ensure chrom, start and stop
# positions columns exist
missing = de_novos[symbols == ""].copy()
missing['end'] = missing["pos"] + missing["ref"].str.len() - 1
# find the HGNC symbols (if any) for the variants
missing = [ get_gene_id(x["chrom"], x["pos"], x['end'], build=build, verbose=True) for i, x in missing.iterrows() ]
symbols[de_novos["symbol"] == ""] = missing
# 360 out of 17000 de novos still lack HGNC symbols. Their consequences are:
#
# consequence count
# ======================== =====
# downstream_gene_variant 17
# intergenic_variant 259
# regulatory_region_variant 63
# upstream_gene_variant 27
#
# In spot checks, these are sufficiently distant from genes that we can't
# add them to the analysis of their nearest gene. We shall analyse these
# per site by giving them mock gene symbols.
missing = de_novos[symbols == ""].copy()
fake = 'fake_symbol.' + missing['chrom'].map(str) + '_' + missing["pos"].map(str)
symbols[symbols == ""] = fake
return symbols |
<|file_name|>missing_symbols.py<|end_file_name|><|fim▁begin|>"""
Copyright (c) 2016 Genome Research Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import time
import sys
import json
try:
import urllib.request as request
from urllib.error import HTTPError
except ImportError:
import urllib2 as request
from urllib2 import HTTPError
import pandas
PREV_TIME = time.time()
IS_PYTHON3 = sys.version[0] == "3"
def fix_missing_gene_symbols(de_novos, build='grch37'):
""" adds gene symbols to variants lacking them.
Args:
de_novos: dataframe of de novo variants
build: whether to use the 'grch37' or 'grch38' build (default=GRCh37)
Returns:
pandas Series of HGNC symbols, with additional annotations for many
variants previously lacking a HGNC symbol.
"""
symbols = de_novos["symbol"].copy()
# get the variants with no gene annotation, ensure chrom, start and stop
# positions columns exist
missing = de_novos[symbols == ""].copy()
missing['end'] = missing["pos"] + missing["ref"].str.len() - 1
# find the HGNC symbols (if any) for the variants
missing = [ get_gene_id(x["chrom"], x["pos"], x['end'], build=build, verbose=True) for i, x in missing.iterrows() ]
symbols[de_novos["symbol"] == ""] = missing
# 360 out of 17000 de novos still lack HGNC symbols. Their consequences are:
#
# consequence count
# ======================== =====
# downstream_gene_variant 17
# intergenic_variant 259
# regulatory_region_variant 63
# upstream_gene_variant 27
#
# In spot checks, these are sufficiently distant from genes that we can't
# add them to the analysis of their nearest gene. We shall analyse these
# per site by giving them mock gene symbols.
missing = de_novos[symbols == ""].copy()
fake = 'fake_symbol.' + missing['chrom'].map(str) + '_' + missing["pos"].map(str)
symbols[symbols == ""] = fake
return symbols
def open_url(url, headers):
<|fim_middle|>
def rate_limit_requests(rate_limit=0.0667):
""" limit ensembl requests to one per 0.067 s
"""
global PREV_TIME
diff = time.time() - PREV_TIME
if diff < rate_limit:
time.sleep(rate_limit - diff)
PREV_TIME = time.time()
def get_gene_id(chrom, start_pos, end_pos, build="grch37", verbose=False, attempts=0):
"""find the hgnc symbol overlapping a variant position
Args:
variant: data frame or list for a variant, containing columns named
"chrom", "start_pos", and "end_pos" for a single variant
build: genome build to find consequences on
verbose: flag indicating whether to print variants as they are checked
Returns:
a character string containing the HGNC symbol.
"""
attempts += 1
if attempts > 5:
raise ValueError("too many attempts, figure out why its failing")
rate_limit_requests()
# define parts of the URL
ext = "overlap/region/human/{0}:{1}-{2}?feature=gene".format(chrom, start_pos, end_pos)
server_dict = {"grch37": "grch37.", "grch38": ""}
base_url = "http://{}rest.ensembl.org".format(server_dict[build])
url = "{0}/{1}".format(base_url, ext)
headers = {"Content-Type" : "application/json"}
if verbose:
print("chr{0}:{1} {2}".format(chrom, start_pos, ext))
response, status_code, requested_headers = open_url(url, headers)
if status_code == 429:
if "retry-after" in requested_headers:
time.sleep(float(requested_headers["retry-after"]))
elif "x-ratelimit-reset" in requested_headers:
time.sleep(int(requested_headers["x-ratelimit-reset"]))
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code in [503, 504]:
time.sleep(30)
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code != 200:
raise ValueError('Invalid Ensembl response: {0}.\nSubmitted '
'URL was: {1}{2}\nheaders: {3}\nresponse: {4}'.format(status_code,
base_url, ext, requested_headers, response))
json_text = json.loads(response)
if len(json_text) > 0:
return json_text[0]["external_name"]
return ""
<|fim▁end|> | """ open url with python libraries
Args:
url:
headers:
Returns:
tuple of http response, http response code, and http headers
"""
req = request.Request(url, headers=headers)
try:
handler = request.urlopen(req)
except HTTPError as e:
handler = e
status_code = handler.getcode()
response = handler.read()
if IS_PYTHON3:
response = response.decode("utf-8")
# parse the headers into a key, value dictionary
headers = dict(zip(map(str.lower, handler.headers.keys()), handler.headers.values()))
return response, status_code, headers |
<|file_name|>missing_symbols.py<|end_file_name|><|fim▁begin|>"""
Copyright (c) 2016 Genome Research Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import time
import sys
import json
try:
import urllib.request as request
from urllib.error import HTTPError
except ImportError:
import urllib2 as request
from urllib2 import HTTPError
import pandas
PREV_TIME = time.time()
IS_PYTHON3 = sys.version[0] == "3"
def fix_missing_gene_symbols(de_novos, build='grch37'):
""" adds gene symbols to variants lacking them.
Args:
de_novos: dataframe of de novo variants
build: whether to use the 'grch37' or 'grch38' build (default=GRCh37)
Returns:
pandas Series of HGNC symbols, with additional annotations for many
variants previously lacking a HGNC symbol.
"""
symbols = de_novos["symbol"].copy()
# get the variants with no gene annotation, ensure chrom, start and stop
# positions columns exist
missing = de_novos[symbols == ""].copy()
missing['end'] = missing["pos"] + missing["ref"].str.len() - 1
# find the HGNC symbols (if any) for the variants
missing = [ get_gene_id(x["chrom"], x["pos"], x['end'], build=build, verbose=True) for i, x in missing.iterrows() ]
symbols[de_novos["symbol"] == ""] = missing
# 360 out of 17000 de novos still lack HGNC symbols. Their consequences are:
#
# consequence count
# ======================== =====
# downstream_gene_variant 17
# intergenic_variant 259
# regulatory_region_variant 63
# upstream_gene_variant 27
#
# In spot checks, these are sufficiently distant from genes that we can't
# add them to the analysis of their nearest gene. We shall analyse these
# per site by giving them mock gene symbols.
missing = de_novos[symbols == ""].copy()
fake = 'fake_symbol.' + missing['chrom'].map(str) + '_' + missing["pos"].map(str)
symbols[symbols == ""] = fake
return symbols
def open_url(url, headers):
""" open url with python libraries
Args:
url:
headers:
Returns:
tuple of http response, http response code, and http headers
"""
req = request.Request(url, headers=headers)
try:
handler = request.urlopen(req)
except HTTPError as e:
handler = e
status_code = handler.getcode()
response = handler.read()
if IS_PYTHON3:
response = response.decode("utf-8")
# parse the headers into a key, value dictionary
headers = dict(zip(map(str.lower, handler.headers.keys()), handler.headers.values()))
return response, status_code, headers
def rate_limit_requests(rate_limit=0.0667):
<|fim_middle|>
def get_gene_id(chrom, start_pos, end_pos, build="grch37", verbose=False, attempts=0):
"""find the hgnc symbol overlapping a variant position
Args:
variant: data frame or list for a variant, containing columns named
"chrom", "start_pos", and "end_pos" for a single variant
build: genome build to find consequences on
verbose: flag indicating whether to print variants as they are checked
Returns:
a character string containing the HGNC symbol.
"""
attempts += 1
if attempts > 5:
raise ValueError("too many attempts, figure out why its failing")
rate_limit_requests()
# define parts of the URL
ext = "overlap/region/human/{0}:{1}-{2}?feature=gene".format(chrom, start_pos, end_pos)
server_dict = {"grch37": "grch37.", "grch38": ""}
base_url = "http://{}rest.ensembl.org".format(server_dict[build])
url = "{0}/{1}".format(base_url, ext)
headers = {"Content-Type" : "application/json"}
if verbose:
print("chr{0}:{1} {2}".format(chrom, start_pos, ext))
response, status_code, requested_headers = open_url(url, headers)
if status_code == 429:
if "retry-after" in requested_headers:
time.sleep(float(requested_headers["retry-after"]))
elif "x-ratelimit-reset" in requested_headers:
time.sleep(int(requested_headers["x-ratelimit-reset"]))
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code in [503, 504]:
time.sleep(30)
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code != 200:
raise ValueError('Invalid Ensembl response: {0}.\nSubmitted '
'URL was: {1}{2}\nheaders: {3}\nresponse: {4}'.format(status_code,
base_url, ext, requested_headers, response))
json_text = json.loads(response)
if len(json_text) > 0:
return json_text[0]["external_name"]
return ""
<|fim▁end|> | """ limit ensembl requests to one per 0.067 s
"""
global PREV_TIME
diff = time.time() - PREV_TIME
if diff < rate_limit:
time.sleep(rate_limit - diff)
PREV_TIME = time.time() |
<|file_name|>missing_symbols.py<|end_file_name|><|fim▁begin|>"""
Copyright (c) 2016 Genome Research Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import time
import sys
import json
try:
import urllib.request as request
from urllib.error import HTTPError
except ImportError:
import urllib2 as request
from urllib2 import HTTPError
import pandas
PREV_TIME = time.time()
IS_PYTHON3 = sys.version[0] == "3"
def fix_missing_gene_symbols(de_novos, build='grch37'):
""" adds gene symbols to variants lacking them.
Args:
de_novos: dataframe of de novo variants
build: whether to use the 'grch37' or 'grch38' build (default=GRCh37)
Returns:
pandas Series of HGNC symbols, with additional annotations for many
variants previously lacking a HGNC symbol.
"""
symbols = de_novos["symbol"].copy()
# get the variants with no gene annotation, ensure chrom, start and stop
# positions columns exist
missing = de_novos[symbols == ""].copy()
missing['end'] = missing["pos"] + missing["ref"].str.len() - 1
# find the HGNC symbols (if any) for the variants
missing = [ get_gene_id(x["chrom"], x["pos"], x['end'], build=build, verbose=True) for i, x in missing.iterrows() ]
symbols[de_novos["symbol"] == ""] = missing
# 360 out of 17000 de novos still lack HGNC symbols. Their consequences are:
#
# consequence count
# ======================== =====
# downstream_gene_variant 17
# intergenic_variant 259
# regulatory_region_variant 63
# upstream_gene_variant 27
#
# In spot checks, these are sufficiently distant from genes that we can't
# add them to the analysis of their nearest gene. We shall analyse these
# per site by giving them mock gene symbols.
missing = de_novos[symbols == ""].copy()
fake = 'fake_symbol.' + missing['chrom'].map(str) + '_' + missing["pos"].map(str)
symbols[symbols == ""] = fake
return symbols
def open_url(url, headers):
""" open url with python libraries
Args:
url:
headers:
Returns:
tuple of http response, http response code, and http headers
"""
req = request.Request(url, headers=headers)
try:
handler = request.urlopen(req)
except HTTPError as e:
handler = e
status_code = handler.getcode()
response = handler.read()
if IS_PYTHON3:
response = response.decode("utf-8")
# parse the headers into a key, value dictionary
headers = dict(zip(map(str.lower, handler.headers.keys()), handler.headers.values()))
return response, status_code, headers
def rate_limit_requests(rate_limit=0.0667):
""" limit ensembl requests to one per 0.067 s
"""
global PREV_TIME
diff = time.time() - PREV_TIME
if diff < rate_limit:
time.sleep(rate_limit - diff)
PREV_TIME = time.time()
def get_gene_id(chrom, start_pos, end_pos, build="grch37", verbose=False, attempts=0):
<|fim_middle|>
<|fim▁end|> | """find the hgnc symbol overlapping a variant position
Args:
variant: data frame or list for a variant, containing columns named
"chrom", "start_pos", and "end_pos" for a single variant
build: genome build to find consequences on
verbose: flag indicating whether to print variants as they are checked
Returns:
a character string containing the HGNC symbol.
"""
attempts += 1
if attempts > 5:
raise ValueError("too many attempts, figure out why its failing")
rate_limit_requests()
# define parts of the URL
ext = "overlap/region/human/{0}:{1}-{2}?feature=gene".format(chrom, start_pos, end_pos)
server_dict = {"grch37": "grch37.", "grch38": ""}
base_url = "http://{}rest.ensembl.org".format(server_dict[build])
url = "{0}/{1}".format(base_url, ext)
headers = {"Content-Type" : "application/json"}
if verbose:
print("chr{0}:{1} {2}".format(chrom, start_pos, ext))
response, status_code, requested_headers = open_url(url, headers)
if status_code == 429:
if "retry-after" in requested_headers:
time.sleep(float(requested_headers["retry-after"]))
elif "x-ratelimit-reset" in requested_headers:
time.sleep(int(requested_headers["x-ratelimit-reset"]))
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code in [503, 504]:
time.sleep(30)
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code != 200:
raise ValueError('Invalid Ensembl response: {0}.\nSubmitted '
'URL was: {1}{2}\nheaders: {3}\nresponse: {4}'.format(status_code,
base_url, ext, requested_headers, response))
json_text = json.loads(response)
if len(json_text) > 0:
return json_text[0]["external_name"]
return "" |
<|file_name|>missing_symbols.py<|end_file_name|><|fim▁begin|>"""
Copyright (c) 2016 Genome Research Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import time
import sys
import json
try:
import urllib.request as request
from urllib.error import HTTPError
except ImportError:
import urllib2 as request
from urllib2 import HTTPError
import pandas
PREV_TIME = time.time()
IS_PYTHON3 = sys.version[0] == "3"
def fix_missing_gene_symbols(de_novos, build='grch37'):
""" adds gene symbols to variants lacking them.
Args:
de_novos: dataframe of de novo variants
build: whether to use the 'grch37' or 'grch38' build (default=GRCh37)
Returns:
pandas Series of HGNC symbols, with additional annotations for many
variants previously lacking a HGNC symbol.
"""
symbols = de_novos["symbol"].copy()
# get the variants with no gene annotation, ensure chrom, start and stop
# positions columns exist
missing = de_novos[symbols == ""].copy()
missing['end'] = missing["pos"] + missing["ref"].str.len() - 1
# find the HGNC symbols (if any) for the variants
missing = [ get_gene_id(x["chrom"], x["pos"], x['end'], build=build, verbose=True) for i, x in missing.iterrows() ]
symbols[de_novos["symbol"] == ""] = missing
# 360 out of 17000 de novos still lack HGNC symbols. Their consequences are:
#
# consequence count
# ======================== =====
# downstream_gene_variant 17
# intergenic_variant 259
# regulatory_region_variant 63
# upstream_gene_variant 27
#
# In spot checks, these are sufficiently distant from genes that we can't
# add them to the analysis of their nearest gene. We shall analyse these
# per site by giving them mock gene symbols.
missing = de_novos[symbols == ""].copy()
fake = 'fake_symbol.' + missing['chrom'].map(str) + '_' + missing["pos"].map(str)
symbols[symbols == ""] = fake
return symbols
def open_url(url, headers):
""" open url with python libraries
Args:
url:
headers:
Returns:
tuple of http response, http response code, and http headers
"""
req = request.Request(url, headers=headers)
try:
handler = request.urlopen(req)
except HTTPError as e:
handler = e
status_code = handler.getcode()
response = handler.read()
if IS_PYTHON3:
<|fim_middle|>
# parse the headers into a key, value dictionary
headers = dict(zip(map(str.lower, handler.headers.keys()), handler.headers.values()))
return response, status_code, headers
def rate_limit_requests(rate_limit=0.0667):
""" limit ensembl requests to one per 0.067 s
"""
global PREV_TIME
diff = time.time() - PREV_TIME
if diff < rate_limit:
time.sleep(rate_limit - diff)
PREV_TIME = time.time()
def get_gene_id(chrom, start_pos, end_pos, build="grch37", verbose=False, attempts=0):
"""find the hgnc symbol overlapping a variant position
Args:
variant: data frame or list for a variant, containing columns named
"chrom", "start_pos", and "end_pos" for a single variant
build: genome build to find consequences on
verbose: flag indicating whether to print variants as they are checked
Returns:
a character string containing the HGNC symbol.
"""
attempts += 1
if attempts > 5:
raise ValueError("too many attempts, figure out why its failing")
rate_limit_requests()
# define parts of the URL
ext = "overlap/region/human/{0}:{1}-{2}?feature=gene".format(chrom, start_pos, end_pos)
server_dict = {"grch37": "grch37.", "grch38": ""}
base_url = "http://{}rest.ensembl.org".format(server_dict[build])
url = "{0}/{1}".format(base_url, ext)
headers = {"Content-Type" : "application/json"}
if verbose:
print("chr{0}:{1} {2}".format(chrom, start_pos, ext))
response, status_code, requested_headers = open_url(url, headers)
if status_code == 429:
if "retry-after" in requested_headers:
time.sleep(float(requested_headers["retry-after"]))
elif "x-ratelimit-reset" in requested_headers:
time.sleep(int(requested_headers["x-ratelimit-reset"]))
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code in [503, 504]:
time.sleep(30)
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code != 200:
raise ValueError('Invalid Ensembl response: {0}.\nSubmitted '
'URL was: {1}{2}\nheaders: {3}\nresponse: {4}'.format(status_code,
base_url, ext, requested_headers, response))
json_text = json.loads(response)
if len(json_text) > 0:
return json_text[0]["external_name"]
return ""
<|fim▁end|> | response = response.decode("utf-8") |
<|file_name|>missing_symbols.py<|end_file_name|><|fim▁begin|>"""
Copyright (c) 2016 Genome Research Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import time
import sys
import json
try:
import urllib.request as request
from urllib.error import HTTPError
except ImportError:
import urllib2 as request
from urllib2 import HTTPError
import pandas
PREV_TIME = time.time()
IS_PYTHON3 = sys.version[0] == "3"
def fix_missing_gene_symbols(de_novos, build='grch37'):
""" adds gene symbols to variants lacking them.
Args:
de_novos: dataframe of de novo variants
build: whether to use the 'grch37' or 'grch38' build (default=GRCh37)
Returns:
pandas Series of HGNC symbols, with additional annotations for many
variants previously lacking a HGNC symbol.
"""
symbols = de_novos["symbol"].copy()
# get the variants with no gene annotation, ensure chrom, start and stop
# positions columns exist
missing = de_novos[symbols == ""].copy()
missing['end'] = missing["pos"] + missing["ref"].str.len() - 1
# find the HGNC symbols (if any) for the variants
missing = [ get_gene_id(x["chrom"], x["pos"], x['end'], build=build, verbose=True) for i, x in missing.iterrows() ]
symbols[de_novos["symbol"] == ""] = missing
# 360 out of 17000 de novos still lack HGNC symbols. Their consequences are:
#
# consequence count
# ======================== =====
# downstream_gene_variant 17
# intergenic_variant 259
# regulatory_region_variant 63
# upstream_gene_variant 27
#
# In spot checks, these are sufficiently distant from genes that we can't
# add them to the analysis of their nearest gene. We shall analyse these
# per site by giving them mock gene symbols.
missing = de_novos[symbols == ""].copy()
fake = 'fake_symbol.' + missing['chrom'].map(str) + '_' + missing["pos"].map(str)
symbols[symbols == ""] = fake
return symbols
def open_url(url, headers):
""" open url with python libraries
Args:
url:
headers:
Returns:
tuple of http response, http response code, and http headers
"""
req = request.Request(url, headers=headers)
try:
handler = request.urlopen(req)
except HTTPError as e:
handler = e
status_code = handler.getcode()
response = handler.read()
if IS_PYTHON3:
response = response.decode("utf-8")
# parse the headers into a key, value dictionary
headers = dict(zip(map(str.lower, handler.headers.keys()), handler.headers.values()))
return response, status_code, headers
def rate_limit_requests(rate_limit=0.0667):
""" limit ensembl requests to one per 0.067 s
"""
global PREV_TIME
diff = time.time() - PREV_TIME
if diff < rate_limit:
<|fim_middle|>
PREV_TIME = time.time()
def get_gene_id(chrom, start_pos, end_pos, build="grch37", verbose=False, attempts=0):
"""find the hgnc symbol overlapping a variant position
Args:
variant: data frame or list for a variant, containing columns named
"chrom", "start_pos", and "end_pos" for a single variant
build: genome build to find consequences on
verbose: flag indicating whether to print variants as they are checked
Returns:
a character string containing the HGNC symbol.
"""
attempts += 1
if attempts > 5:
raise ValueError("too many attempts, figure out why its failing")
rate_limit_requests()
# define parts of the URL
ext = "overlap/region/human/{0}:{1}-{2}?feature=gene".format(chrom, start_pos, end_pos)
server_dict = {"grch37": "grch37.", "grch38": ""}
base_url = "http://{}rest.ensembl.org".format(server_dict[build])
url = "{0}/{1}".format(base_url, ext)
headers = {"Content-Type" : "application/json"}
if verbose:
print("chr{0}:{1} {2}".format(chrom, start_pos, ext))
response, status_code, requested_headers = open_url(url, headers)
if status_code == 429:
if "retry-after" in requested_headers:
time.sleep(float(requested_headers["retry-after"]))
elif "x-ratelimit-reset" in requested_headers:
time.sleep(int(requested_headers["x-ratelimit-reset"]))
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code in [503, 504]:
time.sleep(30)
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code != 200:
raise ValueError('Invalid Ensembl response: {0}.\nSubmitted '
'URL was: {1}{2}\nheaders: {3}\nresponse: {4}'.format(status_code,
base_url, ext, requested_headers, response))
json_text = json.loads(response)
if len(json_text) > 0:
return json_text[0]["external_name"]
return ""
<|fim▁end|> | time.sleep(rate_limit - diff) |
<|file_name|>missing_symbols.py<|end_file_name|><|fim▁begin|>"""
Copyright (c) 2016 Genome Research Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import time
import sys
import json
try:
import urllib.request as request
from urllib.error import HTTPError
except ImportError:
import urllib2 as request
from urllib2 import HTTPError
import pandas
PREV_TIME = time.time()
IS_PYTHON3 = sys.version[0] == "3"
def fix_missing_gene_symbols(de_novos, build='grch37'):
""" adds gene symbols to variants lacking them.
Args:
de_novos: dataframe of de novo variants
build: whether to use the 'grch37' or 'grch38' build (default=GRCh37)
Returns:
pandas Series of HGNC symbols, with additional annotations for many
variants previously lacking a HGNC symbol.
"""
symbols = de_novos["symbol"].copy()
# get the variants with no gene annotation, ensure chrom, start and stop
# positions columns exist
missing = de_novos[symbols == ""].copy()
missing['end'] = missing["pos"] + missing["ref"].str.len() - 1
# find the HGNC symbols (if any) for the variants
missing = [ get_gene_id(x["chrom"], x["pos"], x['end'], build=build, verbose=True) for i, x in missing.iterrows() ]
symbols[de_novos["symbol"] == ""] = missing
# 360 out of 17000 de novos still lack HGNC symbols. Their consequences are:
#
# consequence count
# ======================== =====
# downstream_gene_variant 17
# intergenic_variant 259
# regulatory_region_variant 63
# upstream_gene_variant 27
#
# In spot checks, these are sufficiently distant from genes that we can't
# add them to the analysis of their nearest gene. We shall analyse these
# per site by giving them mock gene symbols.
missing = de_novos[symbols == ""].copy()
fake = 'fake_symbol.' + missing['chrom'].map(str) + '_' + missing["pos"].map(str)
symbols[symbols == ""] = fake
return symbols
def open_url(url, headers):
""" open url with python libraries
Args:
url:
headers:
Returns:
tuple of http response, http response code, and http headers
"""
req = request.Request(url, headers=headers)
try:
handler = request.urlopen(req)
except HTTPError as e:
handler = e
status_code = handler.getcode()
response = handler.read()
if IS_PYTHON3:
response = response.decode("utf-8")
# parse the headers into a key, value dictionary
headers = dict(zip(map(str.lower, handler.headers.keys()), handler.headers.values()))
return response, status_code, headers
def rate_limit_requests(rate_limit=0.0667):
""" limit ensembl requests to one per 0.067 s
"""
global PREV_TIME
diff = time.time() - PREV_TIME
if diff < rate_limit:
time.sleep(rate_limit - diff)
PREV_TIME = time.time()
def get_gene_id(chrom, start_pos, end_pos, build="grch37", verbose=False, attempts=0):
"""find the hgnc symbol overlapping a variant position
Args:
variant: data frame or list for a variant, containing columns named
"chrom", "start_pos", and "end_pos" for a single variant
build: genome build to find consequences on
verbose: flag indicating whether to print variants as they are checked
Returns:
a character string containing the HGNC symbol.
"""
attempts += 1
if attempts > 5:
<|fim_middle|>
rate_limit_requests()
# define parts of the URL
ext = "overlap/region/human/{0}:{1}-{2}?feature=gene".format(chrom, start_pos, end_pos)
server_dict = {"grch37": "grch37.", "grch38": ""}
base_url = "http://{}rest.ensembl.org".format(server_dict[build])
url = "{0}/{1}".format(base_url, ext)
headers = {"Content-Type" : "application/json"}
if verbose:
print("chr{0}:{1} {2}".format(chrom, start_pos, ext))
response, status_code, requested_headers = open_url(url, headers)
if status_code == 429:
if "retry-after" in requested_headers:
time.sleep(float(requested_headers["retry-after"]))
elif "x-ratelimit-reset" in requested_headers:
time.sleep(int(requested_headers["x-ratelimit-reset"]))
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code in [503, 504]:
time.sleep(30)
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code != 200:
raise ValueError('Invalid Ensembl response: {0}.\nSubmitted '
'URL was: {1}{2}\nheaders: {3}\nresponse: {4}'.format(status_code,
base_url, ext, requested_headers, response))
json_text = json.loads(response)
if len(json_text) > 0:
return json_text[0]["external_name"]
return ""
<|fim▁end|> | raise ValueError("too many attempts, figure out why its failing") |
<|file_name|>missing_symbols.py<|end_file_name|><|fim▁begin|>"""
Copyright (c) 2016 Genome Research Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import time
import sys
import json
try:
import urllib.request as request
from urllib.error import HTTPError
except ImportError:
import urllib2 as request
from urllib2 import HTTPError
import pandas
PREV_TIME = time.time()
IS_PYTHON3 = sys.version[0] == "3"
def fix_missing_gene_symbols(de_novos, build='grch37'):
""" adds gene symbols to variants lacking them.
Args:
de_novos: dataframe of de novo variants
build: whether to use the 'grch37' or 'grch38' build (default=GRCh37)
Returns:
pandas Series of HGNC symbols, with additional annotations for many
variants previously lacking a HGNC symbol.
"""
symbols = de_novos["symbol"].copy()
# get the variants with no gene annotation, ensure chrom, start and stop
# positions columns exist
missing = de_novos[symbols == ""].copy()
missing['end'] = missing["pos"] + missing["ref"].str.len() - 1
# find the HGNC symbols (if any) for the variants
missing = [ get_gene_id(x["chrom"], x["pos"], x['end'], build=build, verbose=True) for i, x in missing.iterrows() ]
symbols[de_novos["symbol"] == ""] = missing
# 360 out of 17000 de novos still lack HGNC symbols. Their consequences are:
#
# consequence count
# ======================== =====
# downstream_gene_variant 17
# intergenic_variant 259
# regulatory_region_variant 63
# upstream_gene_variant 27
#
# In spot checks, these are sufficiently distant from genes that we can't
# add them to the analysis of their nearest gene. We shall analyse these
# per site by giving them mock gene symbols.
missing = de_novos[symbols == ""].copy()
fake = 'fake_symbol.' + missing['chrom'].map(str) + '_' + missing["pos"].map(str)
symbols[symbols == ""] = fake
return symbols
def open_url(url, headers):
""" open url with python libraries
Args:
url:
headers:
Returns:
tuple of http response, http response code, and http headers
"""
req = request.Request(url, headers=headers)
try:
handler = request.urlopen(req)
except HTTPError as e:
handler = e
status_code = handler.getcode()
response = handler.read()
if IS_PYTHON3:
response = response.decode("utf-8")
# parse the headers into a key, value dictionary
headers = dict(zip(map(str.lower, handler.headers.keys()), handler.headers.values()))
return response, status_code, headers
def rate_limit_requests(rate_limit=0.0667):
""" limit ensembl requests to one per 0.067 s
"""
global PREV_TIME
diff = time.time() - PREV_TIME
if diff < rate_limit:
time.sleep(rate_limit - diff)
PREV_TIME = time.time()
def get_gene_id(chrom, start_pos, end_pos, build="grch37", verbose=False, attempts=0):
"""find the hgnc symbol overlapping a variant position
Args:
variant: data frame or list for a variant, containing columns named
"chrom", "start_pos", and "end_pos" for a single variant
build: genome build to find consequences on
verbose: flag indicating whether to print variants as they are checked
Returns:
a character string containing the HGNC symbol.
"""
attempts += 1
if attempts > 5:
raise ValueError("too many attempts, figure out why its failing")
rate_limit_requests()
# define parts of the URL
ext = "overlap/region/human/{0}:{1}-{2}?feature=gene".format(chrom, start_pos, end_pos)
server_dict = {"grch37": "grch37.", "grch38": ""}
base_url = "http://{}rest.ensembl.org".format(server_dict[build])
url = "{0}/{1}".format(base_url, ext)
headers = {"Content-Type" : "application/json"}
if verbose:
<|fim_middle|>
response, status_code, requested_headers = open_url(url, headers)
if status_code == 429:
if "retry-after" in requested_headers:
time.sleep(float(requested_headers["retry-after"]))
elif "x-ratelimit-reset" in requested_headers:
time.sleep(int(requested_headers["x-ratelimit-reset"]))
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code in [503, 504]:
time.sleep(30)
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code != 200:
raise ValueError('Invalid Ensembl response: {0}.\nSubmitted '
'URL was: {1}{2}\nheaders: {3}\nresponse: {4}'.format(status_code,
base_url, ext, requested_headers, response))
json_text = json.loads(response)
if len(json_text) > 0:
return json_text[0]["external_name"]
return ""
<|fim▁end|> | print("chr{0}:{1} {2}".format(chrom, start_pos, ext)) |
<|file_name|>missing_symbols.py<|end_file_name|><|fim▁begin|>"""
Copyright (c) 2016 Genome Research Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import time
import sys
import json
try:
import urllib.request as request
from urllib.error import HTTPError
except ImportError:
import urllib2 as request
from urllib2 import HTTPError
import pandas
PREV_TIME = time.time()
IS_PYTHON3 = sys.version[0] == "3"
def fix_missing_gene_symbols(de_novos, build='grch37'):
""" adds gene symbols to variants lacking them.
Args:
de_novos: dataframe of de novo variants
build: whether to use the 'grch37' or 'grch38' build (default=GRCh37)
Returns:
pandas Series of HGNC symbols, with additional annotations for many
variants previously lacking a HGNC symbol.
"""
symbols = de_novos["symbol"].copy()
# get the variants with no gene annotation, ensure chrom, start and stop
# positions columns exist
missing = de_novos[symbols == ""].copy()
missing['end'] = missing["pos"] + missing["ref"].str.len() - 1
# find the HGNC symbols (if any) for the variants
missing = [ get_gene_id(x["chrom"], x["pos"], x['end'], build=build, verbose=True) for i, x in missing.iterrows() ]
symbols[de_novos["symbol"] == ""] = missing
# 360 out of 17000 de novos still lack HGNC symbols. Their consequences are:
#
# consequence count
# ======================== =====
# downstream_gene_variant 17
# intergenic_variant 259
# regulatory_region_variant 63
# upstream_gene_variant 27
#
# In spot checks, these are sufficiently distant from genes that we can't
# add them to the analysis of their nearest gene. We shall analyse these
# per site by giving them mock gene symbols.
missing = de_novos[symbols == ""].copy()
fake = 'fake_symbol.' + missing['chrom'].map(str) + '_' + missing["pos"].map(str)
symbols[symbols == ""] = fake
return symbols
def open_url(url, headers):
""" open url with python libraries
Args:
url:
headers:
Returns:
tuple of http response, http response code, and http headers
"""
req = request.Request(url, headers=headers)
try:
handler = request.urlopen(req)
except HTTPError as e:
handler = e
status_code = handler.getcode()
response = handler.read()
if IS_PYTHON3:
response = response.decode("utf-8")
# parse the headers into a key, value dictionary
headers = dict(zip(map(str.lower, handler.headers.keys()), handler.headers.values()))
return response, status_code, headers
def rate_limit_requests(rate_limit=0.0667):
""" limit ensembl requests to one per 0.067 s
"""
global PREV_TIME
diff = time.time() - PREV_TIME
if diff < rate_limit:
time.sleep(rate_limit - diff)
PREV_TIME = time.time()
def get_gene_id(chrom, start_pos, end_pos, build="grch37", verbose=False, attempts=0):
"""find the hgnc symbol overlapping a variant position
Args:
variant: data frame or list for a variant, containing columns named
"chrom", "start_pos", and "end_pos" for a single variant
build: genome build to find consequences on
verbose: flag indicating whether to print variants as they are checked
Returns:
a character string containing the HGNC symbol.
"""
attempts += 1
if attempts > 5:
raise ValueError("too many attempts, figure out why its failing")
rate_limit_requests()
# define parts of the URL
ext = "overlap/region/human/{0}:{1}-{2}?feature=gene".format(chrom, start_pos, end_pos)
server_dict = {"grch37": "grch37.", "grch38": ""}
base_url = "http://{}rest.ensembl.org".format(server_dict[build])
url = "{0}/{1}".format(base_url, ext)
headers = {"Content-Type" : "application/json"}
if verbose:
print("chr{0}:{1} {2}".format(chrom, start_pos, ext))
response, status_code, requested_headers = open_url(url, headers)
if status_code == 429:
<|fim_middle|>
elif status_code in [503, 504]:
time.sleep(30)
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code != 200:
raise ValueError('Invalid Ensembl response: {0}.\nSubmitted '
'URL was: {1}{2}\nheaders: {3}\nresponse: {4}'.format(status_code,
base_url, ext, requested_headers, response))
json_text = json.loads(response)
if len(json_text) > 0:
return json_text[0]["external_name"]
return ""
<|fim▁end|> | if "retry-after" in requested_headers:
time.sleep(float(requested_headers["retry-after"]))
elif "x-ratelimit-reset" in requested_headers:
time.sleep(int(requested_headers["x-ratelimit-reset"]))
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts) |
<|file_name|>missing_symbols.py<|end_file_name|><|fim▁begin|>"""
Copyright (c) 2016 Genome Research Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import time
import sys
import json
try:
import urllib.request as request
from urllib.error import HTTPError
except ImportError:
import urllib2 as request
from urllib2 import HTTPError
import pandas
PREV_TIME = time.time()
IS_PYTHON3 = sys.version[0] == "3"
def fix_missing_gene_symbols(de_novos, build='grch37'):
""" adds gene symbols to variants lacking them.
Args:
de_novos: dataframe of de novo variants
build: whether to use the 'grch37' or 'grch38' build (default=GRCh37)
Returns:
pandas Series of HGNC symbols, with additional annotations for many
variants previously lacking a HGNC symbol.
"""
symbols = de_novos["symbol"].copy()
# get the variants with no gene annotation, ensure chrom, start and stop
# positions columns exist
missing = de_novos[symbols == ""].copy()
missing['end'] = missing["pos"] + missing["ref"].str.len() - 1
# find the HGNC symbols (if any) for the variants
missing = [ get_gene_id(x["chrom"], x["pos"], x['end'], build=build, verbose=True) for i, x in missing.iterrows() ]
symbols[de_novos["symbol"] == ""] = missing
# 360 out of 17000 de novos still lack HGNC symbols. Their consequences are:
#
# consequence count
# ======================== =====
# downstream_gene_variant 17
# intergenic_variant 259
# regulatory_region_variant 63
# upstream_gene_variant 27
#
# In spot checks, these are sufficiently distant from genes that we can't
# add them to the analysis of their nearest gene. We shall analyse these
# per site by giving them mock gene symbols.
missing = de_novos[symbols == ""].copy()
fake = 'fake_symbol.' + missing['chrom'].map(str) + '_' + missing["pos"].map(str)
symbols[symbols == ""] = fake
return symbols
def open_url(url, headers):
""" open url with python libraries
Args:
url:
headers:
Returns:
tuple of http response, http response code, and http headers
"""
req = request.Request(url, headers=headers)
try:
handler = request.urlopen(req)
except HTTPError as e:
handler = e
status_code = handler.getcode()
response = handler.read()
if IS_PYTHON3:
response = response.decode("utf-8")
# parse the headers into a key, value dictionary
headers = dict(zip(map(str.lower, handler.headers.keys()), handler.headers.values()))
return response, status_code, headers
def rate_limit_requests(rate_limit=0.0667):
""" limit ensembl requests to one per 0.067 s
"""
global PREV_TIME
diff = time.time() - PREV_TIME
if diff < rate_limit:
time.sleep(rate_limit - diff)
PREV_TIME = time.time()
def get_gene_id(chrom, start_pos, end_pos, build="grch37", verbose=False, attempts=0):
"""find the hgnc symbol overlapping a variant position
Args:
variant: data frame or list for a variant, containing columns named
"chrom", "start_pos", and "end_pos" for a single variant
build: genome build to find consequences on
verbose: flag indicating whether to print variants as they are checked
Returns:
a character string containing the HGNC symbol.
"""
attempts += 1
if attempts > 5:
raise ValueError("too many attempts, figure out why its failing")
rate_limit_requests()
# define parts of the URL
ext = "overlap/region/human/{0}:{1}-{2}?feature=gene".format(chrom, start_pos, end_pos)
server_dict = {"grch37": "grch37.", "grch38": ""}
base_url = "http://{}rest.ensembl.org".format(server_dict[build])
url = "{0}/{1}".format(base_url, ext)
headers = {"Content-Type" : "application/json"}
if verbose:
print("chr{0}:{1} {2}".format(chrom, start_pos, ext))
response, status_code, requested_headers = open_url(url, headers)
if status_code == 429:
if "retry-after" in requested_headers:
<|fim_middle|>
elif "x-ratelimit-reset" in requested_headers:
time.sleep(int(requested_headers["x-ratelimit-reset"]))
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code in [503, 504]:
time.sleep(30)
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code != 200:
raise ValueError('Invalid Ensembl response: {0}.\nSubmitted '
'URL was: {1}{2}\nheaders: {3}\nresponse: {4}'.format(status_code,
base_url, ext, requested_headers, response))
json_text = json.loads(response)
if len(json_text) > 0:
return json_text[0]["external_name"]
return ""
<|fim▁end|> | time.sleep(float(requested_headers["retry-after"])) |
<|file_name|>missing_symbols.py<|end_file_name|><|fim▁begin|>"""
Copyright (c) 2016 Genome Research Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import time
import sys
import json
try:
import urllib.request as request
from urllib.error import HTTPError
except ImportError:
import urllib2 as request
from urllib2 import HTTPError
import pandas
PREV_TIME = time.time()
IS_PYTHON3 = sys.version[0] == "3"
def fix_missing_gene_symbols(de_novos, build='grch37'):
""" adds gene symbols to variants lacking them.
Args:
de_novos: dataframe of de novo variants
build: whether to use the 'grch37' or 'grch38' build (default=GRCh37)
Returns:
pandas Series of HGNC symbols, with additional annotations for many
variants previously lacking a HGNC symbol.
"""
symbols = de_novos["symbol"].copy()
# get the variants with no gene annotation, ensure chrom, start and stop
# positions columns exist
missing = de_novos[symbols == ""].copy()
missing['end'] = missing["pos"] + missing["ref"].str.len() - 1
# find the HGNC symbols (if any) for the variants
missing = [ get_gene_id(x["chrom"], x["pos"], x['end'], build=build, verbose=True) for i, x in missing.iterrows() ]
symbols[de_novos["symbol"] == ""] = missing
# 360 out of 17000 de novos still lack HGNC symbols. Their consequences are:
#
# consequence count
# ======================== =====
# downstream_gene_variant 17
# intergenic_variant 259
# regulatory_region_variant 63
# upstream_gene_variant 27
#
# In spot checks, these are sufficiently distant from genes that we can't
# add them to the analysis of their nearest gene. We shall analyse these
# per site by giving them mock gene symbols.
missing = de_novos[symbols == ""].copy()
fake = 'fake_symbol.' + missing['chrom'].map(str) + '_' + missing["pos"].map(str)
symbols[symbols == ""] = fake
return symbols
def open_url(url, headers):
""" open url with python libraries
Args:
url:
headers:
Returns:
tuple of http response, http response code, and http headers
"""
req = request.Request(url, headers=headers)
try:
handler = request.urlopen(req)
except HTTPError as e:
handler = e
status_code = handler.getcode()
response = handler.read()
if IS_PYTHON3:
response = response.decode("utf-8")
# parse the headers into a key, value dictionary
headers = dict(zip(map(str.lower, handler.headers.keys()), handler.headers.values()))
return response, status_code, headers
def rate_limit_requests(rate_limit=0.0667):
""" limit ensembl requests to one per 0.067 s
"""
global PREV_TIME
diff = time.time() - PREV_TIME
if diff < rate_limit:
time.sleep(rate_limit - diff)
PREV_TIME = time.time()
def get_gene_id(chrom, start_pos, end_pos, build="grch37", verbose=False, attempts=0):
"""find the hgnc symbol overlapping a variant position
Args:
variant: data frame or list for a variant, containing columns named
"chrom", "start_pos", and "end_pos" for a single variant
build: genome build to find consequences on
verbose: flag indicating whether to print variants as they are checked
Returns:
a character string containing the HGNC symbol.
"""
attempts += 1
if attempts > 5:
raise ValueError("too many attempts, figure out why its failing")
rate_limit_requests()
# define parts of the URL
ext = "overlap/region/human/{0}:{1}-{2}?feature=gene".format(chrom, start_pos, end_pos)
server_dict = {"grch37": "grch37.", "grch38": ""}
base_url = "http://{}rest.ensembl.org".format(server_dict[build])
url = "{0}/{1}".format(base_url, ext)
headers = {"Content-Type" : "application/json"}
if verbose:
print("chr{0}:{1} {2}".format(chrom, start_pos, ext))
response, status_code, requested_headers = open_url(url, headers)
if status_code == 429:
if "retry-after" in requested_headers:
time.sleep(float(requested_headers["retry-after"]))
elif "x-ratelimit-reset" in requested_headers:
<|fim_middle|>
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code in [503, 504]:
time.sleep(30)
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code != 200:
raise ValueError('Invalid Ensembl response: {0}.\nSubmitted '
'URL was: {1}{2}\nheaders: {3}\nresponse: {4}'.format(status_code,
base_url, ext, requested_headers, response))
json_text = json.loads(response)
if len(json_text) > 0:
return json_text[0]["external_name"]
return ""
<|fim▁end|> | time.sleep(int(requested_headers["x-ratelimit-reset"])) |
<|file_name|>missing_symbols.py<|end_file_name|><|fim▁begin|>"""
Copyright (c) 2016 Genome Research Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import time
import sys
import json
try:
import urllib.request as request
from urllib.error import HTTPError
except ImportError:
import urllib2 as request
from urllib2 import HTTPError
import pandas
PREV_TIME = time.time()
IS_PYTHON3 = sys.version[0] == "3"
def fix_missing_gene_symbols(de_novos, build='grch37'):
""" adds gene symbols to variants lacking them.
Args:
de_novos: dataframe of de novo variants
build: whether to use the 'grch37' or 'grch38' build (default=GRCh37)
Returns:
pandas Series of HGNC symbols, with additional annotations for many
variants previously lacking a HGNC symbol.
"""
symbols = de_novos["symbol"].copy()
# get the variants with no gene annotation, ensure chrom, start and stop
# positions columns exist
missing = de_novos[symbols == ""].copy()
missing['end'] = missing["pos"] + missing["ref"].str.len() - 1
# find the HGNC symbols (if any) for the variants
missing = [ get_gene_id(x["chrom"], x["pos"], x['end'], build=build, verbose=True) for i, x in missing.iterrows() ]
symbols[de_novos["symbol"] == ""] = missing
# 360 out of 17000 de novos still lack HGNC symbols. Their consequences are:
#
# consequence count
# ======================== =====
# downstream_gene_variant 17
# intergenic_variant 259
# regulatory_region_variant 63
# upstream_gene_variant 27
#
# In spot checks, these are sufficiently distant from genes that we can't
# add them to the analysis of their nearest gene. We shall analyse these
# per site by giving them mock gene symbols.
missing = de_novos[symbols == ""].copy()
fake = 'fake_symbol.' + missing['chrom'].map(str) + '_' + missing["pos"].map(str)
symbols[symbols == ""] = fake
return symbols
def open_url(url, headers):
""" open url with python libraries
Args:
url:
headers:
Returns:
tuple of http response, http response code, and http headers
"""
req = request.Request(url, headers=headers)
try:
handler = request.urlopen(req)
except HTTPError as e:
handler = e
status_code = handler.getcode()
response = handler.read()
if IS_PYTHON3:
response = response.decode("utf-8")
# parse the headers into a key, value dictionary
headers = dict(zip(map(str.lower, handler.headers.keys()), handler.headers.values()))
return response, status_code, headers
def rate_limit_requests(rate_limit=0.0667):
""" limit ensembl requests to one per 0.067 s
"""
global PREV_TIME
diff = time.time() - PREV_TIME
if diff < rate_limit:
time.sleep(rate_limit - diff)
PREV_TIME = time.time()
def get_gene_id(chrom, start_pos, end_pos, build="grch37", verbose=False, attempts=0):
"""find the hgnc symbol overlapping a variant position
Args:
variant: data frame or list for a variant, containing columns named
"chrom", "start_pos", and "end_pos" for a single variant
build: genome build to find consequences on
verbose: flag indicating whether to print variants as they are checked
Returns:
a character string containing the HGNC symbol.
"""
attempts += 1
if attempts > 5:
raise ValueError("too many attempts, figure out why its failing")
rate_limit_requests()
# define parts of the URL
ext = "overlap/region/human/{0}:{1}-{2}?feature=gene".format(chrom, start_pos, end_pos)
server_dict = {"grch37": "grch37.", "grch38": ""}
base_url = "http://{}rest.ensembl.org".format(server_dict[build])
url = "{0}/{1}".format(base_url, ext)
headers = {"Content-Type" : "application/json"}
if verbose:
print("chr{0}:{1} {2}".format(chrom, start_pos, ext))
response, status_code, requested_headers = open_url(url, headers)
if status_code == 429:
if "retry-after" in requested_headers:
time.sleep(float(requested_headers["retry-after"]))
elif "x-ratelimit-reset" in requested_headers:
time.sleep(int(requested_headers["x-ratelimit-reset"]))
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code in [503, 504]:
<|fim_middle|>
elif status_code != 200:
raise ValueError('Invalid Ensembl response: {0}.\nSubmitted '
'URL was: {1}{2}\nheaders: {3}\nresponse: {4}'.format(status_code,
base_url, ext, requested_headers, response))
json_text = json.loads(response)
if len(json_text) > 0:
return json_text[0]["external_name"]
return ""
<|fim▁end|> | time.sleep(30)
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts) |
<|file_name|>missing_symbols.py<|end_file_name|><|fim▁begin|>"""
Copyright (c) 2016 Genome Research Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import time
import sys
import json
try:
import urllib.request as request
from urllib.error import HTTPError
except ImportError:
import urllib2 as request
from urllib2 import HTTPError
import pandas
PREV_TIME = time.time()
IS_PYTHON3 = sys.version[0] == "3"
def fix_missing_gene_symbols(de_novos, build='grch37'):
""" adds gene symbols to variants lacking them.
Args:
de_novos: dataframe of de novo variants
build: whether to use the 'grch37' or 'grch38' build (default=GRCh37)
Returns:
pandas Series of HGNC symbols, with additional annotations for many
variants previously lacking a HGNC symbol.
"""
symbols = de_novos["symbol"].copy()
# get the variants with no gene annotation, ensure chrom, start and stop
# positions columns exist
missing = de_novos[symbols == ""].copy()
missing['end'] = missing["pos"] + missing["ref"].str.len() - 1
# find the HGNC symbols (if any) for the variants
missing = [ get_gene_id(x["chrom"], x["pos"], x['end'], build=build, verbose=True) for i, x in missing.iterrows() ]
symbols[de_novos["symbol"] == ""] = missing
# 360 out of 17000 de novos still lack HGNC symbols. Their consequences are:
#
# consequence count
# ======================== =====
# downstream_gene_variant 17
# intergenic_variant 259
# regulatory_region_variant 63
# upstream_gene_variant 27
#
# In spot checks, these are sufficiently distant from genes that we can't
# add them to the analysis of their nearest gene. We shall analyse these
# per site by giving them mock gene symbols.
missing = de_novos[symbols == ""].copy()
fake = 'fake_symbol.' + missing['chrom'].map(str) + '_' + missing["pos"].map(str)
symbols[symbols == ""] = fake
return symbols
def open_url(url, headers):
""" open url with python libraries
Args:
url:
headers:
Returns:
tuple of http response, http response code, and http headers
"""
req = request.Request(url, headers=headers)
try:
handler = request.urlopen(req)
except HTTPError as e:
handler = e
status_code = handler.getcode()
response = handler.read()
if IS_PYTHON3:
response = response.decode("utf-8")
# parse the headers into a key, value dictionary
headers = dict(zip(map(str.lower, handler.headers.keys()), handler.headers.values()))
return response, status_code, headers
def rate_limit_requests(rate_limit=0.0667):
""" limit ensembl requests to one per 0.067 s
"""
global PREV_TIME
diff = time.time() - PREV_TIME
if diff < rate_limit:
time.sleep(rate_limit - diff)
PREV_TIME = time.time()
def get_gene_id(chrom, start_pos, end_pos, build="grch37", verbose=False, attempts=0):
"""find the hgnc symbol overlapping a variant position
Args:
variant: data frame or list for a variant, containing columns named
"chrom", "start_pos", and "end_pos" for a single variant
build: genome build to find consequences on
verbose: flag indicating whether to print variants as they are checked
Returns:
a character string containing the HGNC symbol.
"""
attempts += 1
if attempts > 5:
raise ValueError("too many attempts, figure out why its failing")
rate_limit_requests()
# define parts of the URL
ext = "overlap/region/human/{0}:{1}-{2}?feature=gene".format(chrom, start_pos, end_pos)
server_dict = {"grch37": "grch37.", "grch38": ""}
base_url = "http://{}rest.ensembl.org".format(server_dict[build])
url = "{0}/{1}".format(base_url, ext)
headers = {"Content-Type" : "application/json"}
if verbose:
print("chr{0}:{1} {2}".format(chrom, start_pos, ext))
response, status_code, requested_headers = open_url(url, headers)
if status_code == 429:
if "retry-after" in requested_headers:
time.sleep(float(requested_headers["retry-after"]))
elif "x-ratelimit-reset" in requested_headers:
time.sleep(int(requested_headers["x-ratelimit-reset"]))
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code in [503, 504]:
time.sleep(30)
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code != 200:
<|fim_middle|>
json_text = json.loads(response)
if len(json_text) > 0:
return json_text[0]["external_name"]
return ""
<|fim▁end|> | raise ValueError('Invalid Ensembl response: {0}.\nSubmitted '
'URL was: {1}{2}\nheaders: {3}\nresponse: {4}'.format(status_code,
base_url, ext, requested_headers, response)) |
<|file_name|>missing_symbols.py<|end_file_name|><|fim▁begin|>"""
Copyright (c) 2016 Genome Research Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import time
import sys
import json
try:
import urllib.request as request
from urllib.error import HTTPError
except ImportError:
import urllib2 as request
from urllib2 import HTTPError
import pandas
PREV_TIME = time.time()
IS_PYTHON3 = sys.version[0] == "3"
def fix_missing_gene_symbols(de_novos, build='grch37'):
""" adds gene symbols to variants lacking them.
Args:
de_novos: dataframe of de novo variants
build: whether to use the 'grch37' or 'grch38' build (default=GRCh37)
Returns:
pandas Series of HGNC symbols, with additional annotations for many
variants previously lacking a HGNC symbol.
"""
symbols = de_novos["symbol"].copy()
# get the variants with no gene annotation, ensure chrom, start and stop
# positions columns exist
missing = de_novos[symbols == ""].copy()
missing['end'] = missing["pos"] + missing["ref"].str.len() - 1
# find the HGNC symbols (if any) for the variants
missing = [ get_gene_id(x["chrom"], x["pos"], x['end'], build=build, verbose=True) for i, x in missing.iterrows() ]
symbols[de_novos["symbol"] == ""] = missing
# 360 out of 17000 de novos still lack HGNC symbols. Their consequences are:
#
# consequence count
# ======================== =====
# downstream_gene_variant 17
# intergenic_variant 259
# regulatory_region_variant 63
# upstream_gene_variant 27
#
# In spot checks, these are sufficiently distant from genes that we can't
# add them to the analysis of their nearest gene. We shall analyse these
# per site by giving them mock gene symbols.
missing = de_novos[symbols == ""].copy()
fake = 'fake_symbol.' + missing['chrom'].map(str) + '_' + missing["pos"].map(str)
symbols[symbols == ""] = fake
return symbols
def open_url(url, headers):
""" open url with python libraries
Args:
url:
headers:
Returns:
tuple of http response, http response code, and http headers
"""
req = request.Request(url, headers=headers)
try:
handler = request.urlopen(req)
except HTTPError as e:
handler = e
status_code = handler.getcode()
response = handler.read()
if IS_PYTHON3:
response = response.decode("utf-8")
# parse the headers into a key, value dictionary
headers = dict(zip(map(str.lower, handler.headers.keys()), handler.headers.values()))
return response, status_code, headers
def rate_limit_requests(rate_limit=0.0667):
""" limit ensembl requests to one per 0.067 s
"""
global PREV_TIME
diff = time.time() - PREV_TIME
if diff < rate_limit:
time.sleep(rate_limit - diff)
PREV_TIME = time.time()
def get_gene_id(chrom, start_pos, end_pos, build="grch37", verbose=False, attempts=0):
"""find the hgnc symbol overlapping a variant position
Args:
variant: data frame or list for a variant, containing columns named
"chrom", "start_pos", and "end_pos" for a single variant
build: genome build to find consequences on
verbose: flag indicating whether to print variants as they are checked
Returns:
a character string containing the HGNC symbol.
"""
attempts += 1
if attempts > 5:
raise ValueError("too many attempts, figure out why its failing")
rate_limit_requests()
# define parts of the URL
ext = "overlap/region/human/{0}:{1}-{2}?feature=gene".format(chrom, start_pos, end_pos)
server_dict = {"grch37": "grch37.", "grch38": ""}
base_url = "http://{}rest.ensembl.org".format(server_dict[build])
url = "{0}/{1}".format(base_url, ext)
headers = {"Content-Type" : "application/json"}
if verbose:
print("chr{0}:{1} {2}".format(chrom, start_pos, ext))
response, status_code, requested_headers = open_url(url, headers)
if status_code == 429:
if "retry-after" in requested_headers:
time.sleep(float(requested_headers["retry-after"]))
elif "x-ratelimit-reset" in requested_headers:
time.sleep(int(requested_headers["x-ratelimit-reset"]))
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code in [503, 504]:
time.sleep(30)
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code != 200:
raise ValueError('Invalid Ensembl response: {0}.\nSubmitted '
'URL was: {1}{2}\nheaders: {3}\nresponse: {4}'.format(status_code,
base_url, ext, requested_headers, response))
json_text = json.loads(response)
if len(json_text) > 0:
<|fim_middle|>
return ""
<|fim▁end|> | return json_text[0]["external_name"] |
<|file_name|>missing_symbols.py<|end_file_name|><|fim▁begin|>"""
Copyright (c) 2016 Genome Research Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import time
import sys
import json
try:
import urllib.request as request
from urllib.error import HTTPError
except ImportError:
import urllib2 as request
from urllib2 import HTTPError
import pandas
PREV_TIME = time.time()
IS_PYTHON3 = sys.version[0] == "3"
def <|fim_middle|>(de_novos, build='grch37'):
""" adds gene symbols to variants lacking them.
Args:
de_novos: dataframe of de novo variants
build: whether to use the 'grch37' or 'grch38' build (default=GRCh37)
Returns:
pandas Series of HGNC symbols, with additional annotations for many
variants previously lacking a HGNC symbol.
"""
symbols = de_novos["symbol"].copy()
# get the variants with no gene annotation, ensure chrom, start and stop
# positions columns exist
missing = de_novos[symbols == ""].copy()
missing['end'] = missing["pos"] + missing["ref"].str.len() - 1
# find the HGNC symbols (if any) for the variants
missing = [ get_gene_id(x["chrom"], x["pos"], x['end'], build=build, verbose=True) for i, x in missing.iterrows() ]
symbols[de_novos["symbol"] == ""] = missing
# 360 out of 17000 de novos still lack HGNC symbols. Their consequences are:
#
# consequence count
# ======================== =====
# downstream_gene_variant 17
# intergenic_variant 259
# regulatory_region_variant 63
# upstream_gene_variant 27
#
# In spot checks, these are sufficiently distant from genes that we can't
# add them to the analysis of their nearest gene. We shall analyse these
# per site by giving them mock gene symbols.
missing = de_novos[symbols == ""].copy()
fake = 'fake_symbol.' + missing['chrom'].map(str) + '_' + missing["pos"].map(str)
symbols[symbols == ""] = fake
return symbols
def open_url(url, headers):
""" open url with python libraries
Args:
url:
headers:
Returns:
tuple of http response, http response code, and http headers
"""
req = request.Request(url, headers=headers)
try:
handler = request.urlopen(req)
except HTTPError as e:
handler = e
status_code = handler.getcode()
response = handler.read()
if IS_PYTHON3:
response = response.decode("utf-8")
# parse the headers into a key, value dictionary
headers = dict(zip(map(str.lower, handler.headers.keys()), handler.headers.values()))
return response, status_code, headers
def rate_limit_requests(rate_limit=0.0667):
""" limit ensembl requests to one per 0.067 s
"""
global PREV_TIME
diff = time.time() - PREV_TIME
if diff < rate_limit:
time.sleep(rate_limit - diff)
PREV_TIME = time.time()
def get_gene_id(chrom, start_pos, end_pos, build="grch37", verbose=False, attempts=0):
"""find the hgnc symbol overlapping a variant position
Args:
variant: data frame or list for a variant, containing columns named
"chrom", "start_pos", and "end_pos" for a single variant
build: genome build to find consequences on
verbose: flag indicating whether to print variants as they are checked
Returns:
a character string containing the HGNC symbol.
"""
attempts += 1
if attempts > 5:
raise ValueError("too many attempts, figure out why its failing")
rate_limit_requests()
# define parts of the URL
ext = "overlap/region/human/{0}:{1}-{2}?feature=gene".format(chrom, start_pos, end_pos)
server_dict = {"grch37": "grch37.", "grch38": ""}
base_url = "http://{}rest.ensembl.org".format(server_dict[build])
url = "{0}/{1}".format(base_url, ext)
headers = {"Content-Type" : "application/json"}
if verbose:
print("chr{0}:{1} {2}".format(chrom, start_pos, ext))
response, status_code, requested_headers = open_url(url, headers)
if status_code == 429:
if "retry-after" in requested_headers:
time.sleep(float(requested_headers["retry-after"]))
elif "x-ratelimit-reset" in requested_headers:
time.sleep(int(requested_headers["x-ratelimit-reset"]))
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code in [503, 504]:
time.sleep(30)
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code != 200:
raise ValueError('Invalid Ensembl response: {0}.\nSubmitted '
'URL was: {1}{2}\nheaders: {3}\nresponse: {4}'.format(status_code,
base_url, ext, requested_headers, response))
json_text = json.loads(response)
if len(json_text) > 0:
return json_text[0]["external_name"]
return ""
<|fim▁end|> | fix_missing_gene_symbols |
<|file_name|>missing_symbols.py<|end_file_name|><|fim▁begin|>"""
Copyright (c) 2016 Genome Research Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import time
import sys
import json
try:
import urllib.request as request
from urllib.error import HTTPError
except ImportError:
import urllib2 as request
from urllib2 import HTTPError
import pandas
PREV_TIME = time.time()
IS_PYTHON3 = sys.version[0] == "3"
def fix_missing_gene_symbols(de_novos, build='grch37'):
""" adds gene symbols to variants lacking them.
Args:
de_novos: dataframe of de novo variants
build: whether to use the 'grch37' or 'grch38' build (default=GRCh37)
Returns:
pandas Series of HGNC symbols, with additional annotations for many
variants previously lacking a HGNC symbol.
"""
symbols = de_novos["symbol"].copy()
# get the variants with no gene annotation, ensure chrom, start and stop
# positions columns exist
missing = de_novos[symbols == ""].copy()
missing['end'] = missing["pos"] + missing["ref"].str.len() - 1
# find the HGNC symbols (if any) for the variants
missing = [ get_gene_id(x["chrom"], x["pos"], x['end'], build=build, verbose=True) for i, x in missing.iterrows() ]
symbols[de_novos["symbol"] == ""] = missing
# 360 out of 17000 de novos still lack HGNC symbols. Their consequences are:
#
# consequence count
# ======================== =====
# downstream_gene_variant 17
# intergenic_variant 259
# regulatory_region_variant 63
# upstream_gene_variant 27
#
# In spot checks, these are sufficiently distant from genes that we can't
# add them to the analysis of their nearest gene. We shall analyse these
# per site by giving them mock gene symbols.
missing = de_novos[symbols == ""].copy()
fake = 'fake_symbol.' + missing['chrom'].map(str) + '_' + missing["pos"].map(str)
symbols[symbols == ""] = fake
return symbols
def <|fim_middle|>(url, headers):
""" open url with python libraries
Args:
url:
headers:
Returns:
tuple of http response, http response code, and http headers
"""
req = request.Request(url, headers=headers)
try:
handler = request.urlopen(req)
except HTTPError as e:
handler = e
status_code = handler.getcode()
response = handler.read()
if IS_PYTHON3:
response = response.decode("utf-8")
# parse the headers into a key, value dictionary
headers = dict(zip(map(str.lower, handler.headers.keys()), handler.headers.values()))
return response, status_code, headers
def rate_limit_requests(rate_limit=0.0667):
""" limit ensembl requests to one per 0.067 s
"""
global PREV_TIME
diff = time.time() - PREV_TIME
if diff < rate_limit:
time.sleep(rate_limit - diff)
PREV_TIME = time.time()
def get_gene_id(chrom, start_pos, end_pos, build="grch37", verbose=False, attempts=0):
"""find the hgnc symbol overlapping a variant position
Args:
variant: data frame or list for a variant, containing columns named
"chrom", "start_pos", and "end_pos" for a single variant
build: genome build to find consequences on
verbose: flag indicating whether to print variants as they are checked
Returns:
a character string containing the HGNC symbol.
"""
attempts += 1
if attempts > 5:
raise ValueError("too many attempts, figure out why its failing")
rate_limit_requests()
# define parts of the URL
ext = "overlap/region/human/{0}:{1}-{2}?feature=gene".format(chrom, start_pos, end_pos)
server_dict = {"grch37": "grch37.", "grch38": ""}
base_url = "http://{}rest.ensembl.org".format(server_dict[build])
url = "{0}/{1}".format(base_url, ext)
headers = {"Content-Type" : "application/json"}
if verbose:
print("chr{0}:{1} {2}".format(chrom, start_pos, ext))
response, status_code, requested_headers = open_url(url, headers)
if status_code == 429:
if "retry-after" in requested_headers:
time.sleep(float(requested_headers["retry-after"]))
elif "x-ratelimit-reset" in requested_headers:
time.sleep(int(requested_headers["x-ratelimit-reset"]))
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code in [503, 504]:
time.sleep(30)
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code != 200:
raise ValueError('Invalid Ensembl response: {0}.\nSubmitted '
'URL was: {1}{2}\nheaders: {3}\nresponse: {4}'.format(status_code,
base_url, ext, requested_headers, response))
json_text = json.loads(response)
if len(json_text) > 0:
return json_text[0]["external_name"]
return ""
<|fim▁end|> | open_url |
<|file_name|>missing_symbols.py<|end_file_name|><|fim▁begin|>"""
Copyright (c) 2016 Genome Research Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import time
import sys
import json
try:
import urllib.request as request
from urllib.error import HTTPError
except ImportError:
import urllib2 as request
from urllib2 import HTTPError
import pandas
PREV_TIME = time.time()
IS_PYTHON3 = sys.version[0] == "3"
def fix_missing_gene_symbols(de_novos, build='grch37'):
""" adds gene symbols to variants lacking them.
Args:
de_novos: dataframe of de novo variants
build: whether to use the 'grch37' or 'grch38' build (default=GRCh37)
Returns:
pandas Series of HGNC symbols, with additional annotations for many
variants previously lacking a HGNC symbol.
"""
symbols = de_novos["symbol"].copy()
# get the variants with no gene annotation, ensure chrom, start and stop
# positions columns exist
missing = de_novos[symbols == ""].copy()
missing['end'] = missing["pos"] + missing["ref"].str.len() - 1
# find the HGNC symbols (if any) for the variants
missing = [ get_gene_id(x["chrom"], x["pos"], x['end'], build=build, verbose=True) for i, x in missing.iterrows() ]
symbols[de_novos["symbol"] == ""] = missing
# 360 out of 17000 de novos still lack HGNC symbols. Their consequences are:
#
# consequence count
# ======================== =====
# downstream_gene_variant 17
# intergenic_variant 259
# regulatory_region_variant 63
# upstream_gene_variant 27
#
# In spot checks, these are sufficiently distant from genes that we can't
# add them to the analysis of their nearest gene. We shall analyse these
# per site by giving them mock gene symbols.
missing = de_novos[symbols == ""].copy()
fake = 'fake_symbol.' + missing['chrom'].map(str) + '_' + missing["pos"].map(str)
symbols[symbols == ""] = fake
return symbols
def open_url(url, headers):
""" open url with python libraries
Args:
url:
headers:
Returns:
tuple of http response, http response code, and http headers
"""
req = request.Request(url, headers=headers)
try:
handler = request.urlopen(req)
except HTTPError as e:
handler = e
status_code = handler.getcode()
response = handler.read()
if IS_PYTHON3:
response = response.decode("utf-8")
# parse the headers into a key, value dictionary
headers = dict(zip(map(str.lower, handler.headers.keys()), handler.headers.values()))
return response, status_code, headers
def <|fim_middle|>(rate_limit=0.0667):
""" limit ensembl requests to one per 0.067 s
"""
global PREV_TIME
diff = time.time() - PREV_TIME
if diff < rate_limit:
time.sleep(rate_limit - diff)
PREV_TIME = time.time()
def get_gene_id(chrom, start_pos, end_pos, build="grch37", verbose=False, attempts=0):
"""find the hgnc symbol overlapping a variant position
Args:
variant: data frame or list for a variant, containing columns named
"chrom", "start_pos", and "end_pos" for a single variant
build: genome build to find consequences on
verbose: flag indicating whether to print variants as they are checked
Returns:
a character string containing the HGNC symbol.
"""
attempts += 1
if attempts > 5:
raise ValueError("too many attempts, figure out why its failing")
rate_limit_requests()
# define parts of the URL
ext = "overlap/region/human/{0}:{1}-{2}?feature=gene".format(chrom, start_pos, end_pos)
server_dict = {"grch37": "grch37.", "grch38": ""}
base_url = "http://{}rest.ensembl.org".format(server_dict[build])
url = "{0}/{1}".format(base_url, ext)
headers = {"Content-Type" : "application/json"}
if verbose:
print("chr{0}:{1} {2}".format(chrom, start_pos, ext))
response, status_code, requested_headers = open_url(url, headers)
if status_code == 429:
if "retry-after" in requested_headers:
time.sleep(float(requested_headers["retry-after"]))
elif "x-ratelimit-reset" in requested_headers:
time.sleep(int(requested_headers["x-ratelimit-reset"]))
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code in [503, 504]:
time.sleep(30)
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code != 200:
raise ValueError('Invalid Ensembl response: {0}.\nSubmitted '
'URL was: {1}{2}\nheaders: {3}\nresponse: {4}'.format(status_code,
base_url, ext, requested_headers, response))
json_text = json.loads(response)
if len(json_text) > 0:
return json_text[0]["external_name"]
return ""
<|fim▁end|> | rate_limit_requests |
<|file_name|>missing_symbols.py<|end_file_name|><|fim▁begin|>"""
Copyright (c) 2016 Genome Research Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import time
import sys
import json
try:
import urllib.request as request
from urllib.error import HTTPError
except ImportError:
import urllib2 as request
from urllib2 import HTTPError
import pandas
PREV_TIME = time.time()
IS_PYTHON3 = sys.version[0] == "3"
def fix_missing_gene_symbols(de_novos, build='grch37'):
""" adds gene symbols to variants lacking them.
Args:
de_novos: dataframe of de novo variants
build: whether to use the 'grch37' or 'grch38' build (default=GRCh37)
Returns:
pandas Series of HGNC symbols, with additional annotations for many
variants previously lacking a HGNC symbol.
"""
symbols = de_novos["symbol"].copy()
# get the variants with no gene annotation, ensure chrom, start and stop
# positions columns exist
missing = de_novos[symbols == ""].copy()
missing['end'] = missing["pos"] + missing["ref"].str.len() - 1
# find the HGNC symbols (if any) for the variants
missing = [ get_gene_id(x["chrom"], x["pos"], x['end'], build=build, verbose=True) for i, x in missing.iterrows() ]
symbols[de_novos["symbol"] == ""] = missing
# 360 out of 17000 de novos still lack HGNC symbols. Their consequences are:
#
# consequence count
# ======================== =====
# downstream_gene_variant 17
# intergenic_variant 259
# regulatory_region_variant 63
# upstream_gene_variant 27
#
# In spot checks, these are sufficiently distant from genes that we can't
# add them to the analysis of their nearest gene. We shall analyse these
# per site by giving them mock gene symbols.
missing = de_novos[symbols == ""].copy()
fake = 'fake_symbol.' + missing['chrom'].map(str) + '_' + missing["pos"].map(str)
symbols[symbols == ""] = fake
return symbols
def open_url(url, headers):
""" open url with python libraries
Args:
url:
headers:
Returns:
tuple of http response, http response code, and http headers
"""
req = request.Request(url, headers=headers)
try:
handler = request.urlopen(req)
except HTTPError as e:
handler = e
status_code = handler.getcode()
response = handler.read()
if IS_PYTHON3:
response = response.decode("utf-8")
# parse the headers into a key, value dictionary
headers = dict(zip(map(str.lower, handler.headers.keys()), handler.headers.values()))
return response, status_code, headers
def rate_limit_requests(rate_limit=0.0667):
""" limit ensembl requests to one per 0.067 s
"""
global PREV_TIME
diff = time.time() - PREV_TIME
if diff < rate_limit:
time.sleep(rate_limit - diff)
PREV_TIME = time.time()
def <|fim_middle|>(chrom, start_pos, end_pos, build="grch37", verbose=False, attempts=0):
"""find the hgnc symbol overlapping a variant position
Args:
variant: data frame or list for a variant, containing columns named
"chrom", "start_pos", and "end_pos" for a single variant
build: genome build to find consequences on
verbose: flag indicating whether to print variants as they are checked
Returns:
a character string containing the HGNC symbol.
"""
attempts += 1
if attempts > 5:
raise ValueError("too many attempts, figure out why its failing")
rate_limit_requests()
# define parts of the URL
ext = "overlap/region/human/{0}:{1}-{2}?feature=gene".format(chrom, start_pos, end_pos)
server_dict = {"grch37": "grch37.", "grch38": ""}
base_url = "http://{}rest.ensembl.org".format(server_dict[build])
url = "{0}/{1}".format(base_url, ext)
headers = {"Content-Type" : "application/json"}
if verbose:
print("chr{0}:{1} {2}".format(chrom, start_pos, ext))
response, status_code, requested_headers = open_url(url, headers)
if status_code == 429:
if "retry-after" in requested_headers:
time.sleep(float(requested_headers["retry-after"]))
elif "x-ratelimit-reset" in requested_headers:
time.sleep(int(requested_headers["x-ratelimit-reset"]))
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code in [503, 504]:
time.sleep(30)
return get_gene_id(chrom, start_pos, end_pos, build, verbose, attempts)
elif status_code != 200:
raise ValueError('Invalid Ensembl response: {0}.\nSubmitted '
'URL was: {1}{2}\nheaders: {3}\nresponse: {4}'.format(status_code,
base_url, ext, requested_headers, response))
json_text = json.loads(response)
if len(json_text) > 0:
return json_text[0]["external_name"]
return ""
<|fim▁end|> | get_gene_id |
<|file_name|>datasources.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 24 12:49:36 2017
@author: drsmith
"""
import os
from .globals import FdpError
def canonicalMachineName(machine=''):
aliases = {'nstxu': ['nstx', 'nstxu', 'nstx-u'],
'diiid': ['diiid', 'diii-d', 'd3d'],
'cmod': ['cmod', 'c-mod']}
for key, value in aliases.items():
if machine.lower() in value:
return key
# invalid machine name
raise FdpError('"{}" is not a valid machine name\n'.format(machine))
MDS_SERVERS = {
'nstxu': {'hostname': 'skylark.pppl.gov',
'port': '8000'},
'diiid': {'hostname': 'atlas.gat.com',
'port': '8000'}
}
EVENT_SERVERS = {
'nstxu': {'hostname': 'skylark.pppl.gov',
'port': '8000'},
'diiid': {'hostname': 'atlas.gat.com',
'port': '8000'},
'ltx': {'hostname': 'lithos.pppl.gov',
'port': '8000'}
}
LOGBOOK_CREDENTIALS = {
'nstxu': {'server': 'sql2008.pppl.gov',
'instance': None,
'username': None,
'password': None,
'database': None,
'port': '62917',
'table': 'entries',
'loginfile': os.path.join(os.getenv('HOME'),<|fim▁hole|>}<|fim▁end|> | 'nstxlogs.sybase_login')
} |
<|file_name|>datasources.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 24 12:49:36 2017
@author: drsmith
"""
import os
from .globals import FdpError
def canonicalMachineName(machine=''):
<|fim_middle|>
MDS_SERVERS = {
'nstxu': {'hostname': 'skylark.pppl.gov',
'port': '8000'},
'diiid': {'hostname': 'atlas.gat.com',
'port': '8000'}
}
EVENT_SERVERS = {
'nstxu': {'hostname': 'skylark.pppl.gov',
'port': '8000'},
'diiid': {'hostname': 'atlas.gat.com',
'port': '8000'},
'ltx': {'hostname': 'lithos.pppl.gov',
'port': '8000'}
}
LOGBOOK_CREDENTIALS = {
'nstxu': {'server': 'sql2008.pppl.gov',
'instance': None,
'username': None,
'password': None,
'database': None,
'port': '62917',
'table': 'entries',
'loginfile': os.path.join(os.getenv('HOME'),
'nstxlogs.sybase_login')
}
}
<|fim▁end|> | aliases = {'nstxu': ['nstx', 'nstxu', 'nstx-u'],
'diiid': ['diiid', 'diii-d', 'd3d'],
'cmod': ['cmod', 'c-mod']}
for key, value in aliases.items():
if machine.lower() in value:
return key
# invalid machine name
raise FdpError('"{}" is not a valid machine name\n'.format(machine)) |
<|file_name|>datasources.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 24 12:49:36 2017
@author: drsmith
"""
import os
from .globals import FdpError
def canonicalMachineName(machine=''):
aliases = {'nstxu': ['nstx', 'nstxu', 'nstx-u'],
'diiid': ['diiid', 'diii-d', 'd3d'],
'cmod': ['cmod', 'c-mod']}
for key, value in aliases.items():
if machine.lower() in value:
<|fim_middle|>
# invalid machine name
raise FdpError('"{}" is not a valid machine name\n'.format(machine))
MDS_SERVERS = {
'nstxu': {'hostname': 'skylark.pppl.gov',
'port': '8000'},
'diiid': {'hostname': 'atlas.gat.com',
'port': '8000'}
}
EVENT_SERVERS = {
'nstxu': {'hostname': 'skylark.pppl.gov',
'port': '8000'},
'diiid': {'hostname': 'atlas.gat.com',
'port': '8000'},
'ltx': {'hostname': 'lithos.pppl.gov',
'port': '8000'}
}
LOGBOOK_CREDENTIALS = {
'nstxu': {'server': 'sql2008.pppl.gov',
'instance': None,
'username': None,
'password': None,
'database': None,
'port': '62917',
'table': 'entries',
'loginfile': os.path.join(os.getenv('HOME'),
'nstxlogs.sybase_login')
}
}
<|fim▁end|> | return key |
<|file_name|>datasources.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 24 12:49:36 2017
@author: drsmith
"""
import os
from .globals import FdpError
def <|fim_middle|>(machine=''):
aliases = {'nstxu': ['nstx', 'nstxu', 'nstx-u'],
'diiid': ['diiid', 'diii-d', 'd3d'],
'cmod': ['cmod', 'c-mod']}
for key, value in aliases.items():
if machine.lower() in value:
return key
# invalid machine name
raise FdpError('"{}" is not a valid machine name\n'.format(machine))
MDS_SERVERS = {
'nstxu': {'hostname': 'skylark.pppl.gov',
'port': '8000'},
'diiid': {'hostname': 'atlas.gat.com',
'port': '8000'}
}
EVENT_SERVERS = {
'nstxu': {'hostname': 'skylark.pppl.gov',
'port': '8000'},
'diiid': {'hostname': 'atlas.gat.com',
'port': '8000'},
'ltx': {'hostname': 'lithos.pppl.gov',
'port': '8000'}
}
LOGBOOK_CREDENTIALS = {
'nstxu': {'server': 'sql2008.pppl.gov',
'instance': None,
'username': None,
'password': None,
'database': None,
'port': '62917',
'table': 'entries',
'loginfile': os.path.join(os.getenv('HOME'),
'nstxlogs.sybase_login')
}
}
<|fim▁end|> | canonicalMachineName |
<|file_name|>oracle_element.py<|end_file_name|><|fim▁begin|># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Reach oracle element used for configuration."""
import dataclasses
from pyreach.gyms import reach_element
@dataclasses.dataclass(frozen=True)
class ReachOracle(reach_element.ReachElement):
"""A Reach Oracle configuration class.
Attributes:
reach_name: The name of the Oracle.
task_code: The task code string.
intent: The intention of the task. This agument is optional and defaults to
an empty string.
success_type: The type of success. This argument is optional and defaults
to an empty string.
is_synchronous: If True, the next Gym observation will synchronize all
observation elements that have this flag set otherwise the next<|fim▁hole|> False.
"""
task_code: str
intent: str = ""
success_type: str = ""
is_synchronous: bool = False<|fim▁end|> | observation is asynchronous. This argument is optional and defaults to |
<|file_name|>oracle_element.py<|end_file_name|><|fim▁begin|># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Reach oracle element used for configuration."""
import dataclasses
from pyreach.gyms import reach_element
@dataclasses.dataclass(frozen=True)
class ReachOracle(reach_element.ReachElement):
<|fim_middle|>
<|fim▁end|> | """A Reach Oracle configuration class.
Attributes:
reach_name: The name of the Oracle.
task_code: The task code string.
intent: The intention of the task. This agument is optional and defaults to
an empty string.
success_type: The type of success. This argument is optional and defaults
to an empty string.
is_synchronous: If True, the next Gym observation will synchronize all
observation elements that have this flag set otherwise the next
observation is asynchronous. This argument is optional and defaults to
False.
"""
task_code: str
intent: str = ""
success_type: str = ""
is_synchronous: bool = False |
<|file_name|>hash_check.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from flask_bcrypt import generate_password_hash
# Change the number of rounds (second argument) until it takes between
# 0.25 and 0.5 seconds to run.
generate_password_hash('password1', 8)<|fim▁end|> | |
<|file_name|>echem_paperplots.py<|end_file_name|><|fim▁begin|>import time, copy
import os, os.path
import sys
import numpy
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from scipy import optimize
from echem_plate_ui import *
from echem_plate_math import *
import pickle
p1='C:/Users/Gregoire/Documents/CaltechWork/echemdrop/2012-9_FeCoNiTi/results/echemplots/2012-9_FeCoNiTi_500C_fastCPCV_plate1_dlist_1066.dat'
p2='C:/Users/Gregoire/Documents/CaltechWork/echemdrop/2012-9_FeCoNiTi/results/echemplots/2012-9_FeCoNiTi_500C_fastCPCV_plate1_dlist_1662.dat'
pill='C:/Users/Gregoire/Documents/CaltechWork/echemdrop/2012-9_FeCoNiTi/results/echemplots/2012-9FeCoNiTi_500C_CAill_plate1_dlist_1164.dat'
os.chdir('C:/Users/Gregoire/Documents/CaltechWork/echemdrop/2012-9_FeCoNiTi/results/echemplots')
vshift=-.24
imult=1.e6
cai0, cai1=(0, 6500)
f=open(p1, mode='r')
d1=pickle.load(f)
f.close()
f=open(p2, mode='r')
d2=pickle.load(f)
f.close()
f=open(pill, mode='r')
dill=pickle.load(f)
f.close()
segd1up, segd1dn=d1['segprops_dlist']
i1up=d1['I(A)'][segd1up['inds']][4:]
lin1up=i1up-d1['I(A)_LinSub'][segd1up['inds']][4:]
v1up=d1['Ewe(V)'][segd1up['inds']][4:]+vshift
i1dn=d1['I(A)'][segd1dn['inds']]
v1dn=d1['Ewe(V)'][segd1dn['inds']]+vshift
i1up*=imult
i1dn*=imult
lin1up*=imult
segd2up, segd2dn=d2['segprops_dlist']
i2up=d2['I(A)'][segd2up['inds']][4:]
lin2up=i2up-d2['I(A)_LinSub'][segd2up['inds']][4:]
v2up=d2['Ewe(V)'][segd2up['inds']][4:]+vshift
i2dn=d2['I(A)'][segd2dn['inds']]
v2dn=d2['Ewe(V)'][segd2dn['inds']]+vshift
i2up*=imult
i2dn*=imult<|fim▁hole|>lin2up*=imult
ica=dill['I(A)_SG'][cai0:cai1]*imult
icadiff=dill['Idiff_time'][cai0:cai1]*imult
tca=dill['t(s)'][cai0:cai1]
tca_cycs=dill['till_cycs']
cycinds=numpy.where((tca_cycs>=tca.min())&(tca_cycs<=tca.max()))[0]
tca_cycs=tca_cycs[cycinds]
iphoto_cycs=dill['Photocurrent_cycs(A)'][cycinds]*imult
pylab.rc('font', family='serif', serif='Times New Roman', size=11)
fig=pylab.figure(figsize=(3.5, 4.5))
#ax1=pylab.subplot(211)
#ax2=pylab.subplot(212)
ax1=fig.add_axes((.2, .6, .74, .35))
ax2=fig.add_axes((.2, .11, .6, .35))
ax3=ax2.twinx()
ax1.plot(v1up, i1up, 'g-', linewidth=1.)
ax1.plot(v1up, lin1up, 'g:', linewidth=1.)
ax1.plot(v1dn, i1dn, 'g--', linewidth=1.)
ax1.plot(v2up, i2up, 'b-', linewidth=1.)
ax1.plot(v2up, lin2up, 'b:', linewidth=1.)
ax1.plot(v2dn, i2dn, 'b--', linewidth=1.)
ax1.set_xlim((-.1, .62))
ax1.set_ylim((-40, 130))
ax1.set_xlabel('Potential (V vs H$_2$O/O$_2$)', fontsize=12)
ax1.set_ylabel('Current ($\mu$A)', fontsize=12)
ax2.plot(tca, ica, 'k-')
ax2.plot(tca, icadiff, 'b--', linewidth=2)
ax2.set_xlim((0, 6.5))
ax2.set_ylim((0, 0.4))
ax3.plot(tca_cycs, iphoto_cycs, 'ro-')
ax3.set_ylim((0, 0.1))
ax2.set_xlabel('Elapsed time (s)', fontsize=12)
ax2.set_ylabel('Current ($\mu$A)', fontsize=12)
ax3.set_ylabel('Photocurrent ($\mu$A)', fontsize=12)
pylab.show()
print ''.join(['%s%.3f' %tup for tup in zip(dill['elements'], dill['compositions'])])
print ''.join(['%s%.3f' %tup for tup in zip(d1['elements'], d1['compositions'])])
print ''.join(['%s%.3f' %tup for tup in zip(d2['elements'], d2['compositions'])])<|fim▁end|> | |
<|file_name|>running_mpi_executables.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
__copyright__ = "Copyright 2013-2014, http://radical.rutgers.edu"
__license__ = "MIT"
import sys
import radical.pilot as rp
# READ: The RADICAL-Pilot documentation:
# http://radicalpilot.readthedocs.org/en/latest
#
# Try running this example with RADICAL_PILOT_VERBOSE=debug set if
# you want to see what happens behind the scenes!
#------------------------------------------------------------------------------
#
def pilot_state_cb (pilot, state):
""" this callback is invoked on all pilot state changes """
print "[Callback]: ComputePilot '%s' state: %s." % (pilot.uid, state)
if state == rp.FAILED:
sys.exit (1)
#------------------------------------------------------------------------------
#
def unit_state_cb (unit, state):
""" this callback is invoked on all unit state changes """
<|fim▁hole|>
# ------------------------------------------------------------------------------
#
if __name__ == "__main__":
# we can optionally pass session name to RP
if len(sys.argv) > 1:
session_name = sys.argv[1]
else:
session_name = None
# Create a new session. No need to try/except this: if session creation
# fails, there is not much we can do anyways...
session = rp.Session(name=session_name)
print "session id: %s" % session.uid
# all other pilot code is now tried/excepted. If an exception is caught, we
# can rely on the session object to exist and be valid, and we can thus tear
# the whole RP stack down via a 'session.close()' call in the 'finally'
# clause...
try:
# Add a Pilot Manager. Pilot managers manage one or more ComputePilots.
pmgr = rp.PilotManager(session=session)
# Register our callback with the PilotManager. This callback will get
# called every time any of the pilots managed by the PilotManager
# change their state.
pmgr.register_callback(pilot_state_cb)
# Define a X-core on stamped that runs for N minutes and
# uses $HOME/radical.pilot.sandbox as sandbox directoy.
pdesc = rp.ComputePilotDescription()
pdesc.resource = "xsede.stampede"
pdesc.runtime = 15 # N minutes
pdesc.cores = 16 # X cores
pdesc.project = "TG-MCB090174"
# Launch the pilot.
pilot = pmgr.submit_pilots(pdesc)
cud_list = []
for unit_count in range(0, 4):
cu = rp.ComputeUnitDescription()
cu.pre_exec = ["module load python intel mvapich2 mpi4py"]
cu.executable = "python"
cu.arguments = ["helloworld_mpi.py"]
cu.input_staging = ["helloworld_mpi.py"]
# These two parameters are relevant to MPI execution:
# 'cores' sets the number of cores required by the task
# 'mpi' identifies the task as an MPI taskg
cu.cores = 8
cu.mpi = True
cud_list.append(cu)
# Combine the ComputePilot, the ComputeUnits and a scheduler via
# a UnitManager object.
umgr = rp.UnitManager(
session=session,
scheduler=rp.SCHED_DIRECT_SUBMISSION)
# Register our callback with the UnitManager. This callback will get
# called every time any of the units managed by the UnitManager
# change their state.
umgr.register_callback(unit_state_cb)
# Add the previously created ComputePilot to the UnitManager.
umgr.add_pilots(pilot)
# Submit the previously created ComputeUnit descriptions to the
# PilotManager. This will trigger the selected scheduler to start
# assigning ComputeUnits to the ComputePilots.
units = umgr.submit_units(cud_list)
# Wait for all compute units to reach a terminal state (DONE or FAILED).
umgr.wait_units()
if not isinstance(units, list):
units = [units]
for unit in units:
print "* Task %s - state: %s, exit code: %s, started: %s, finished: %s, stdout: %s" \
% (unit.uid, unit.state, unit.exit_code, unit.start_time, unit.stop_time, unit.stdout)
except Exception as e:
# Something unexpected happened in the pilot code above
print "caught Exception: %s" % e
raise
except (KeyboardInterrupt, SystemExit) as e:
# the callback called sys.exit(), and we can here catch the
# corresponding KeyboardInterrupt exception for shutdown. We also catch
# SystemExit (which gets raised if the main threads exits for some other
# reason).
print "need to exit now: %s" % e
finally:
# always clean up the session, no matter if we caught an exception or
# not.
print "closing session"
session.close ()
# the above is equivalent to
#
# session.close (cleanup=True, terminate=True)
#
# it will thus both clean out the session's database record, and kill
# all remaining pilots (none in our example).
#-------------------------------------------------------------------------------<|fim▁end|> | print "[Callback]: ComputeUnit '%s' state: %s." % (unit.uid, state)
if state == rp.FAILED:
sys.exit (1) |
<|file_name|>running_mpi_executables.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
__copyright__ = "Copyright 2013-2014, http://radical.rutgers.edu"
__license__ = "MIT"
import sys
import radical.pilot as rp
# READ: The RADICAL-Pilot documentation:
# http://radicalpilot.readthedocs.org/en/latest
#
# Try running this example with RADICAL_PILOT_VERBOSE=debug set if
# you want to see what happens behind the scenes!
#------------------------------------------------------------------------------
#
def pilot_state_cb (pilot, state):
<|fim_middle|>
#------------------------------------------------------------------------------
#
def unit_state_cb (unit, state):
""" this callback is invoked on all unit state changes """
print "[Callback]: ComputeUnit '%s' state: %s." % (unit.uid, state)
if state == rp.FAILED:
sys.exit (1)
# ------------------------------------------------------------------------------
#
if __name__ == "__main__":
# we can optionally pass session name to RP
if len(sys.argv) > 1:
session_name = sys.argv[1]
else:
session_name = None
# Create a new session. No need to try/except this: if session creation
# fails, there is not much we can do anyways...
session = rp.Session(name=session_name)
print "session id: %s" % session.uid
# all other pilot code is now tried/excepted. If an exception is caught, we
# can rely on the session object to exist and be valid, and we can thus tear
# the whole RP stack down via a 'session.close()' call in the 'finally'
# clause...
try:
# Add a Pilot Manager. Pilot managers manage one or more ComputePilots.
pmgr = rp.PilotManager(session=session)
# Register our callback with the PilotManager. This callback will get
# called every time any of the pilots managed by the PilotManager
# change their state.
pmgr.register_callback(pilot_state_cb)
# Define a X-core on stamped that runs for N minutes and
# uses $HOME/radical.pilot.sandbox as sandbox directoy.
pdesc = rp.ComputePilotDescription()
pdesc.resource = "xsede.stampede"
pdesc.runtime = 15 # N minutes
pdesc.cores = 16 # X cores
pdesc.project = "TG-MCB090174"
# Launch the pilot.
pilot = pmgr.submit_pilots(pdesc)
cud_list = []
for unit_count in range(0, 4):
cu = rp.ComputeUnitDescription()
cu.pre_exec = ["module load python intel mvapich2 mpi4py"]
cu.executable = "python"
cu.arguments = ["helloworld_mpi.py"]
cu.input_staging = ["helloworld_mpi.py"]
# These two parameters are relevant to MPI execution:
# 'cores' sets the number of cores required by the task
# 'mpi' identifies the task as an MPI taskg
cu.cores = 8
cu.mpi = True
cud_list.append(cu)
# Combine the ComputePilot, the ComputeUnits and a scheduler via
# a UnitManager object.
umgr = rp.UnitManager(
session=session,
scheduler=rp.SCHED_DIRECT_SUBMISSION)
# Register our callback with the UnitManager. This callback will get
# called every time any of the units managed by the UnitManager
# change their state.
umgr.register_callback(unit_state_cb)
# Add the previously created ComputePilot to the UnitManager.
umgr.add_pilots(pilot)
# Submit the previously created ComputeUnit descriptions to the
# PilotManager. This will trigger the selected scheduler to start
# assigning ComputeUnits to the ComputePilots.
units = umgr.submit_units(cud_list)
# Wait for all compute units to reach a terminal state (DONE or FAILED).
umgr.wait_units()
if not isinstance(units, list):
units = [units]
for unit in units:
print "* Task %s - state: %s, exit code: %s, started: %s, finished: %s, stdout: %s" \
% (unit.uid, unit.state, unit.exit_code, unit.start_time, unit.stop_time, unit.stdout)
except Exception as e:
# Something unexpected happened in the pilot code above
print "caught Exception: %s" % e
raise
except (KeyboardInterrupt, SystemExit) as e:
# the callback called sys.exit(), and we can here catch the
# corresponding KeyboardInterrupt exception for shutdown. We also catch
# SystemExit (which gets raised if the main threads exits for some other
# reason).
print "need to exit now: %s" % e
finally:
# always clean up the session, no matter if we caught an exception or
# not.
print "closing session"
session.close ()
# the above is equivalent to
#
# session.close (cleanup=True, terminate=True)
#
# it will thus both clean out the session's database record, and kill
# all remaining pilots (none in our example).
#-------------------------------------------------------------------------------
<|fim▁end|> | """ this callback is invoked on all pilot state changes """
print "[Callback]: ComputePilot '%s' state: %s." % (pilot.uid, state)
if state == rp.FAILED:
sys.exit (1) |
<|file_name|>running_mpi_executables.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
__copyright__ = "Copyright 2013-2014, http://radical.rutgers.edu"
__license__ = "MIT"
import sys
import radical.pilot as rp
# READ: The RADICAL-Pilot documentation:
# http://radicalpilot.readthedocs.org/en/latest
#
# Try running this example with RADICAL_PILOT_VERBOSE=debug set if
# you want to see what happens behind the scenes!
#------------------------------------------------------------------------------
#
def pilot_state_cb (pilot, state):
""" this callback is invoked on all pilot state changes """
print "[Callback]: ComputePilot '%s' state: %s." % (pilot.uid, state)
if state == rp.FAILED:
sys.exit (1)
#------------------------------------------------------------------------------
#
def unit_state_cb (unit, state):
<|fim_middle|>
# ------------------------------------------------------------------------------
#
if __name__ == "__main__":
# we can optionally pass session name to RP
if len(sys.argv) > 1:
session_name = sys.argv[1]
else:
session_name = None
# Create a new session. No need to try/except this: if session creation
# fails, there is not much we can do anyways...
session = rp.Session(name=session_name)
print "session id: %s" % session.uid
# all other pilot code is now tried/excepted. If an exception is caught, we
# can rely on the session object to exist and be valid, and we can thus tear
# the whole RP stack down via a 'session.close()' call in the 'finally'
# clause...
try:
# Add a Pilot Manager. Pilot managers manage one or more ComputePilots.
pmgr = rp.PilotManager(session=session)
# Register our callback with the PilotManager. This callback will get
# called every time any of the pilots managed by the PilotManager
# change their state.
pmgr.register_callback(pilot_state_cb)
# Define a X-core on stamped that runs for N minutes and
# uses $HOME/radical.pilot.sandbox as sandbox directoy.
pdesc = rp.ComputePilotDescription()
pdesc.resource = "xsede.stampede"
pdesc.runtime = 15 # N minutes
pdesc.cores = 16 # X cores
pdesc.project = "TG-MCB090174"
# Launch the pilot.
pilot = pmgr.submit_pilots(pdesc)
cud_list = []
for unit_count in range(0, 4):
cu = rp.ComputeUnitDescription()
cu.pre_exec = ["module load python intel mvapich2 mpi4py"]
cu.executable = "python"
cu.arguments = ["helloworld_mpi.py"]
cu.input_staging = ["helloworld_mpi.py"]
# These two parameters are relevant to MPI execution:
# 'cores' sets the number of cores required by the task
# 'mpi' identifies the task as an MPI taskg
cu.cores = 8
cu.mpi = True
cud_list.append(cu)
# Combine the ComputePilot, the ComputeUnits and a scheduler via
# a UnitManager object.
umgr = rp.UnitManager(
session=session,
scheduler=rp.SCHED_DIRECT_SUBMISSION)
# Register our callback with the UnitManager. This callback will get
# called every time any of the units managed by the UnitManager
# change their state.
umgr.register_callback(unit_state_cb)
# Add the previously created ComputePilot to the UnitManager.
umgr.add_pilots(pilot)
# Submit the previously created ComputeUnit descriptions to the
# PilotManager. This will trigger the selected scheduler to start
# assigning ComputeUnits to the ComputePilots.
units = umgr.submit_units(cud_list)
# Wait for all compute units to reach a terminal state (DONE or FAILED).
umgr.wait_units()
if not isinstance(units, list):
units = [units]
for unit in units:
print "* Task %s - state: %s, exit code: %s, started: %s, finished: %s, stdout: %s" \
% (unit.uid, unit.state, unit.exit_code, unit.start_time, unit.stop_time, unit.stdout)
except Exception as e:
# Something unexpected happened in the pilot code above
print "caught Exception: %s" % e
raise
except (KeyboardInterrupt, SystemExit) as e:
# the callback called sys.exit(), and we can here catch the
# corresponding KeyboardInterrupt exception for shutdown. We also catch
# SystemExit (which gets raised if the main threads exits for some other
# reason).
print "need to exit now: %s" % e
finally:
# always clean up the session, no matter if we caught an exception or
# not.
print "closing session"
session.close ()
# the above is equivalent to
#
# session.close (cleanup=True, terminate=True)
#
# it will thus both clean out the session's database record, and kill
# all remaining pilots (none in our example).
#-------------------------------------------------------------------------------
<|fim▁end|> | """ this callback is invoked on all unit state changes """
print "[Callback]: ComputeUnit '%s' state: %s." % (unit.uid, state)
if state == rp.FAILED:
sys.exit (1) |
<|file_name|>running_mpi_executables.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
__copyright__ = "Copyright 2013-2014, http://radical.rutgers.edu"
__license__ = "MIT"
import sys
import radical.pilot as rp
# READ: The RADICAL-Pilot documentation:
# http://radicalpilot.readthedocs.org/en/latest
#
# Try running this example with RADICAL_PILOT_VERBOSE=debug set if
# you want to see what happens behind the scenes!
#------------------------------------------------------------------------------
#
def pilot_state_cb (pilot, state):
""" this callback is invoked on all pilot state changes """
print "[Callback]: ComputePilot '%s' state: %s." % (pilot.uid, state)
if state == rp.FAILED:
<|fim_middle|>
#------------------------------------------------------------------------------
#
def unit_state_cb (unit, state):
""" this callback is invoked on all unit state changes """
print "[Callback]: ComputeUnit '%s' state: %s." % (unit.uid, state)
if state == rp.FAILED:
sys.exit (1)
# ------------------------------------------------------------------------------
#
if __name__ == "__main__":
# we can optionally pass session name to RP
if len(sys.argv) > 1:
session_name = sys.argv[1]
else:
session_name = None
# Create a new session. No need to try/except this: if session creation
# fails, there is not much we can do anyways...
session = rp.Session(name=session_name)
print "session id: %s" % session.uid
# all other pilot code is now tried/excepted. If an exception is caught, we
# can rely on the session object to exist and be valid, and we can thus tear
# the whole RP stack down via a 'session.close()' call in the 'finally'
# clause...
try:
# Add a Pilot Manager. Pilot managers manage one or more ComputePilots.
pmgr = rp.PilotManager(session=session)
# Register our callback with the PilotManager. This callback will get
# called every time any of the pilots managed by the PilotManager
# change their state.
pmgr.register_callback(pilot_state_cb)
# Define a X-core on stamped that runs for N minutes and
# uses $HOME/radical.pilot.sandbox as sandbox directoy.
pdesc = rp.ComputePilotDescription()
pdesc.resource = "xsede.stampede"
pdesc.runtime = 15 # N minutes
pdesc.cores = 16 # X cores
pdesc.project = "TG-MCB090174"
# Launch the pilot.
pilot = pmgr.submit_pilots(pdesc)
cud_list = []
for unit_count in range(0, 4):
cu = rp.ComputeUnitDescription()
cu.pre_exec = ["module load python intel mvapich2 mpi4py"]
cu.executable = "python"
cu.arguments = ["helloworld_mpi.py"]
cu.input_staging = ["helloworld_mpi.py"]
# These two parameters are relevant to MPI execution:
# 'cores' sets the number of cores required by the task
# 'mpi' identifies the task as an MPI taskg
cu.cores = 8
cu.mpi = True
cud_list.append(cu)
# Combine the ComputePilot, the ComputeUnits and a scheduler via
# a UnitManager object.
umgr = rp.UnitManager(
session=session,
scheduler=rp.SCHED_DIRECT_SUBMISSION)
# Register our callback with the UnitManager. This callback will get
# called every time any of the units managed by the UnitManager
# change their state.
umgr.register_callback(unit_state_cb)
# Add the previously created ComputePilot to the UnitManager.
umgr.add_pilots(pilot)
# Submit the previously created ComputeUnit descriptions to the
# PilotManager. This will trigger the selected scheduler to start
# assigning ComputeUnits to the ComputePilots.
units = umgr.submit_units(cud_list)
# Wait for all compute units to reach a terminal state (DONE or FAILED).
umgr.wait_units()
if not isinstance(units, list):
units = [units]
for unit in units:
print "* Task %s - state: %s, exit code: %s, started: %s, finished: %s, stdout: %s" \
% (unit.uid, unit.state, unit.exit_code, unit.start_time, unit.stop_time, unit.stdout)
except Exception as e:
# Something unexpected happened in the pilot code above
print "caught Exception: %s" % e
raise
except (KeyboardInterrupt, SystemExit) as e:
# the callback called sys.exit(), and we can here catch the
# corresponding KeyboardInterrupt exception for shutdown. We also catch
# SystemExit (which gets raised if the main threads exits for some other
# reason).
print "need to exit now: %s" % e
finally:
# always clean up the session, no matter if we caught an exception or
# not.
print "closing session"
session.close ()
# the above is equivalent to
#
# session.close (cleanup=True, terminate=True)
#
# it will thus both clean out the session's database record, and kill
# all remaining pilots (none in our example).
#-------------------------------------------------------------------------------
<|fim▁end|> | sys.exit (1) |
<|file_name|>running_mpi_executables.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
__copyright__ = "Copyright 2013-2014, http://radical.rutgers.edu"
__license__ = "MIT"
import sys
import radical.pilot as rp
# READ: The RADICAL-Pilot documentation:
# http://radicalpilot.readthedocs.org/en/latest
#
# Try running this example with RADICAL_PILOT_VERBOSE=debug set if
# you want to see what happens behind the scenes!
#------------------------------------------------------------------------------
#
def pilot_state_cb (pilot, state):
""" this callback is invoked on all pilot state changes """
print "[Callback]: ComputePilot '%s' state: %s." % (pilot.uid, state)
if state == rp.FAILED:
sys.exit (1)
#------------------------------------------------------------------------------
#
def unit_state_cb (unit, state):
""" this callback is invoked on all unit state changes """
print "[Callback]: ComputeUnit '%s' state: %s." % (unit.uid, state)
if state == rp.FAILED:
<|fim_middle|>
# ------------------------------------------------------------------------------
#
if __name__ == "__main__":
# we can optionally pass session name to RP
if len(sys.argv) > 1:
session_name = sys.argv[1]
else:
session_name = None
# Create a new session. No need to try/except this: if session creation
# fails, there is not much we can do anyways...
session = rp.Session(name=session_name)
print "session id: %s" % session.uid
# all other pilot code is now tried/excepted. If an exception is caught, we
# can rely on the session object to exist and be valid, and we can thus tear
# the whole RP stack down via a 'session.close()' call in the 'finally'
# clause...
try:
# Add a Pilot Manager. Pilot managers manage one or more ComputePilots.
pmgr = rp.PilotManager(session=session)
# Register our callback with the PilotManager. This callback will get
# called every time any of the pilots managed by the PilotManager
# change their state.
pmgr.register_callback(pilot_state_cb)
# Define a X-core on stamped that runs for N minutes and
# uses $HOME/radical.pilot.sandbox as sandbox directoy.
pdesc = rp.ComputePilotDescription()
pdesc.resource = "xsede.stampede"
pdesc.runtime = 15 # N minutes
pdesc.cores = 16 # X cores
pdesc.project = "TG-MCB090174"
# Launch the pilot.
pilot = pmgr.submit_pilots(pdesc)
cud_list = []
for unit_count in range(0, 4):
cu = rp.ComputeUnitDescription()
cu.pre_exec = ["module load python intel mvapich2 mpi4py"]
cu.executable = "python"
cu.arguments = ["helloworld_mpi.py"]
cu.input_staging = ["helloworld_mpi.py"]
# These two parameters are relevant to MPI execution:
# 'cores' sets the number of cores required by the task
# 'mpi' identifies the task as an MPI taskg
cu.cores = 8
cu.mpi = True
cud_list.append(cu)
# Combine the ComputePilot, the ComputeUnits and a scheduler via
# a UnitManager object.
umgr = rp.UnitManager(
session=session,
scheduler=rp.SCHED_DIRECT_SUBMISSION)
# Register our callback with the UnitManager. This callback will get
# called every time any of the units managed by the UnitManager
# change their state.
umgr.register_callback(unit_state_cb)
# Add the previously created ComputePilot to the UnitManager.
umgr.add_pilots(pilot)
# Submit the previously created ComputeUnit descriptions to the
# PilotManager. This will trigger the selected scheduler to start
# assigning ComputeUnits to the ComputePilots.
units = umgr.submit_units(cud_list)
# Wait for all compute units to reach a terminal state (DONE or FAILED).
umgr.wait_units()
if not isinstance(units, list):
units = [units]
for unit in units:
print "* Task %s - state: %s, exit code: %s, started: %s, finished: %s, stdout: %s" \
% (unit.uid, unit.state, unit.exit_code, unit.start_time, unit.stop_time, unit.stdout)
except Exception as e:
# Something unexpected happened in the pilot code above
print "caught Exception: %s" % e
raise
except (KeyboardInterrupt, SystemExit) as e:
# the callback called sys.exit(), and we can here catch the
# corresponding KeyboardInterrupt exception for shutdown. We also catch
# SystemExit (which gets raised if the main threads exits for some other
# reason).
print "need to exit now: %s" % e
finally:
# always clean up the session, no matter if we caught an exception or
# not.
print "closing session"
session.close ()
# the above is equivalent to
#
# session.close (cleanup=True, terminate=True)
#
# it will thus both clean out the session's database record, and kill
# all remaining pilots (none in our example).
#-------------------------------------------------------------------------------
<|fim▁end|> | sys.exit (1) |
<|file_name|>running_mpi_executables.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
__copyright__ = "Copyright 2013-2014, http://radical.rutgers.edu"
__license__ = "MIT"
import sys
import radical.pilot as rp
# READ: The RADICAL-Pilot documentation:
# http://radicalpilot.readthedocs.org/en/latest
#
# Try running this example with RADICAL_PILOT_VERBOSE=debug set if
# you want to see what happens behind the scenes!
#------------------------------------------------------------------------------
#
def pilot_state_cb (pilot, state):
""" this callback is invoked on all pilot state changes """
print "[Callback]: ComputePilot '%s' state: %s." % (pilot.uid, state)
if state == rp.FAILED:
sys.exit (1)
#------------------------------------------------------------------------------
#
def unit_state_cb (unit, state):
""" this callback is invoked on all unit state changes """
print "[Callback]: ComputeUnit '%s' state: %s." % (unit.uid, state)
if state == rp.FAILED:
sys.exit (1)
# ------------------------------------------------------------------------------
#
if __name__ == "__main__":
# we can optionally pass session name to RP
<|fim_middle|>
#-------------------------------------------------------------------------------
<|fim▁end|> | if len(sys.argv) > 1:
session_name = sys.argv[1]
else:
session_name = None
# Create a new session. No need to try/except this: if session creation
# fails, there is not much we can do anyways...
session = rp.Session(name=session_name)
print "session id: %s" % session.uid
# all other pilot code is now tried/excepted. If an exception is caught, we
# can rely on the session object to exist and be valid, and we can thus tear
# the whole RP stack down via a 'session.close()' call in the 'finally'
# clause...
try:
# Add a Pilot Manager. Pilot managers manage one or more ComputePilots.
pmgr = rp.PilotManager(session=session)
# Register our callback with the PilotManager. This callback will get
# called every time any of the pilots managed by the PilotManager
# change their state.
pmgr.register_callback(pilot_state_cb)
# Define a X-core on stamped that runs for N minutes and
# uses $HOME/radical.pilot.sandbox as sandbox directoy.
pdesc = rp.ComputePilotDescription()
pdesc.resource = "xsede.stampede"
pdesc.runtime = 15 # N minutes
pdesc.cores = 16 # X cores
pdesc.project = "TG-MCB090174"
# Launch the pilot.
pilot = pmgr.submit_pilots(pdesc)
cud_list = []
for unit_count in range(0, 4):
cu = rp.ComputeUnitDescription()
cu.pre_exec = ["module load python intel mvapich2 mpi4py"]
cu.executable = "python"
cu.arguments = ["helloworld_mpi.py"]
cu.input_staging = ["helloworld_mpi.py"]
# These two parameters are relevant to MPI execution:
# 'cores' sets the number of cores required by the task
# 'mpi' identifies the task as an MPI taskg
cu.cores = 8
cu.mpi = True
cud_list.append(cu)
# Combine the ComputePilot, the ComputeUnits and a scheduler via
# a UnitManager object.
umgr = rp.UnitManager(
session=session,
scheduler=rp.SCHED_DIRECT_SUBMISSION)
# Register our callback with the UnitManager. This callback will get
# called every time any of the units managed by the UnitManager
# change their state.
umgr.register_callback(unit_state_cb)
# Add the previously created ComputePilot to the UnitManager.
umgr.add_pilots(pilot)
# Submit the previously created ComputeUnit descriptions to the
# PilotManager. This will trigger the selected scheduler to start
# assigning ComputeUnits to the ComputePilots.
units = umgr.submit_units(cud_list)
# Wait for all compute units to reach a terminal state (DONE or FAILED).
umgr.wait_units()
if not isinstance(units, list):
units = [units]
for unit in units:
print "* Task %s - state: %s, exit code: %s, started: %s, finished: %s, stdout: %s" \
% (unit.uid, unit.state, unit.exit_code, unit.start_time, unit.stop_time, unit.stdout)
except Exception as e:
# Something unexpected happened in the pilot code above
print "caught Exception: %s" % e
raise
except (KeyboardInterrupt, SystemExit) as e:
# the callback called sys.exit(), and we can here catch the
# corresponding KeyboardInterrupt exception for shutdown. We also catch
# SystemExit (which gets raised if the main threads exits for some other
# reason).
print "need to exit now: %s" % e
finally:
# always clean up the session, no matter if we caught an exception or
# not.
print "closing session"
session.close ()
# the above is equivalent to
#
# session.close (cleanup=True, terminate=True)
#
# it will thus both clean out the session's database record, and kill
# all remaining pilots (none in our example). |
<|file_name|>running_mpi_executables.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
__copyright__ = "Copyright 2013-2014, http://radical.rutgers.edu"
__license__ = "MIT"
import sys
import radical.pilot as rp
# READ: The RADICAL-Pilot documentation:
# http://radicalpilot.readthedocs.org/en/latest
#
# Try running this example with RADICAL_PILOT_VERBOSE=debug set if
# you want to see what happens behind the scenes!
#------------------------------------------------------------------------------
#
def pilot_state_cb (pilot, state):
""" this callback is invoked on all pilot state changes """
print "[Callback]: ComputePilot '%s' state: %s." % (pilot.uid, state)
if state == rp.FAILED:
sys.exit (1)
#------------------------------------------------------------------------------
#
def unit_state_cb (unit, state):
""" this callback is invoked on all unit state changes """
print "[Callback]: ComputeUnit '%s' state: %s." % (unit.uid, state)
if state == rp.FAILED:
sys.exit (1)
# ------------------------------------------------------------------------------
#
if __name__ == "__main__":
# we can optionally pass session name to RP
if len(sys.argv) > 1:
<|fim_middle|>
else:
session_name = None
# Create a new session. No need to try/except this: if session creation
# fails, there is not much we can do anyways...
session = rp.Session(name=session_name)
print "session id: %s" % session.uid
# all other pilot code is now tried/excepted. If an exception is caught, we
# can rely on the session object to exist and be valid, and we can thus tear
# the whole RP stack down via a 'session.close()' call in the 'finally'
# clause...
try:
# Add a Pilot Manager. Pilot managers manage one or more ComputePilots.
pmgr = rp.PilotManager(session=session)
# Register our callback with the PilotManager. This callback will get
# called every time any of the pilots managed by the PilotManager
# change their state.
pmgr.register_callback(pilot_state_cb)
# Define a X-core on stamped that runs for N minutes and
# uses $HOME/radical.pilot.sandbox as sandbox directoy.
pdesc = rp.ComputePilotDescription()
pdesc.resource = "xsede.stampede"
pdesc.runtime = 15 # N minutes
pdesc.cores = 16 # X cores
pdesc.project = "TG-MCB090174"
# Launch the pilot.
pilot = pmgr.submit_pilots(pdesc)
cud_list = []
for unit_count in range(0, 4):
cu = rp.ComputeUnitDescription()
cu.pre_exec = ["module load python intel mvapich2 mpi4py"]
cu.executable = "python"
cu.arguments = ["helloworld_mpi.py"]
cu.input_staging = ["helloworld_mpi.py"]
# These two parameters are relevant to MPI execution:
# 'cores' sets the number of cores required by the task
# 'mpi' identifies the task as an MPI taskg
cu.cores = 8
cu.mpi = True
cud_list.append(cu)
# Combine the ComputePilot, the ComputeUnits and a scheduler via
# a UnitManager object.
umgr = rp.UnitManager(
session=session,
scheduler=rp.SCHED_DIRECT_SUBMISSION)
# Register our callback with the UnitManager. This callback will get
# called every time any of the units managed by the UnitManager
# change their state.
umgr.register_callback(unit_state_cb)
# Add the previously created ComputePilot to the UnitManager.
umgr.add_pilots(pilot)
# Submit the previously created ComputeUnit descriptions to the
# PilotManager. This will trigger the selected scheduler to start
# assigning ComputeUnits to the ComputePilots.
units = umgr.submit_units(cud_list)
# Wait for all compute units to reach a terminal state (DONE or FAILED).
umgr.wait_units()
if not isinstance(units, list):
units = [units]
for unit in units:
print "* Task %s - state: %s, exit code: %s, started: %s, finished: %s, stdout: %s" \
% (unit.uid, unit.state, unit.exit_code, unit.start_time, unit.stop_time, unit.stdout)
except Exception as e:
# Something unexpected happened in the pilot code above
print "caught Exception: %s" % e
raise
except (KeyboardInterrupt, SystemExit) as e:
# the callback called sys.exit(), and we can here catch the
# corresponding KeyboardInterrupt exception for shutdown. We also catch
# SystemExit (which gets raised if the main threads exits for some other
# reason).
print "need to exit now: %s" % e
finally:
# always clean up the session, no matter if we caught an exception or
# not.
print "closing session"
session.close ()
# the above is equivalent to
#
# session.close (cleanup=True, terminate=True)
#
# it will thus both clean out the session's database record, and kill
# all remaining pilots (none in our example).
#-------------------------------------------------------------------------------
<|fim▁end|> | session_name = sys.argv[1] |
<|file_name|>running_mpi_executables.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
__copyright__ = "Copyright 2013-2014, http://radical.rutgers.edu"
__license__ = "MIT"
import sys
import radical.pilot as rp
# READ: The RADICAL-Pilot documentation:
# http://radicalpilot.readthedocs.org/en/latest
#
# Try running this example with RADICAL_PILOT_VERBOSE=debug set if
# you want to see what happens behind the scenes!
#------------------------------------------------------------------------------
#
def pilot_state_cb (pilot, state):
""" this callback is invoked on all pilot state changes """
print "[Callback]: ComputePilot '%s' state: %s." % (pilot.uid, state)
if state == rp.FAILED:
sys.exit (1)
#------------------------------------------------------------------------------
#
def unit_state_cb (unit, state):
""" this callback is invoked on all unit state changes """
print "[Callback]: ComputeUnit '%s' state: %s." % (unit.uid, state)
if state == rp.FAILED:
sys.exit (1)
# ------------------------------------------------------------------------------
#
if __name__ == "__main__":
# we can optionally pass session name to RP
if len(sys.argv) > 1:
session_name = sys.argv[1]
else:
<|fim_middle|>
# Create a new session. No need to try/except this: if session creation
# fails, there is not much we can do anyways...
session = rp.Session(name=session_name)
print "session id: %s" % session.uid
# all other pilot code is now tried/excepted. If an exception is caught, we
# can rely on the session object to exist and be valid, and we can thus tear
# the whole RP stack down via a 'session.close()' call in the 'finally'
# clause...
try:
# Add a Pilot Manager. Pilot managers manage one or more ComputePilots.
pmgr = rp.PilotManager(session=session)
# Register our callback with the PilotManager. This callback will get
# called every time any of the pilots managed by the PilotManager
# change their state.
pmgr.register_callback(pilot_state_cb)
# Define a X-core on stamped that runs for N minutes and
# uses $HOME/radical.pilot.sandbox as sandbox directoy.
pdesc = rp.ComputePilotDescription()
pdesc.resource = "xsede.stampede"
pdesc.runtime = 15 # N minutes
pdesc.cores = 16 # X cores
pdesc.project = "TG-MCB090174"
# Launch the pilot.
pilot = pmgr.submit_pilots(pdesc)
cud_list = []
for unit_count in range(0, 4):
cu = rp.ComputeUnitDescription()
cu.pre_exec = ["module load python intel mvapich2 mpi4py"]
cu.executable = "python"
cu.arguments = ["helloworld_mpi.py"]
cu.input_staging = ["helloworld_mpi.py"]
# These two parameters are relevant to MPI execution:
# 'cores' sets the number of cores required by the task
# 'mpi' identifies the task as an MPI taskg
cu.cores = 8
cu.mpi = True
cud_list.append(cu)
# Combine the ComputePilot, the ComputeUnits and a scheduler via
# a UnitManager object.
umgr = rp.UnitManager(
session=session,
scheduler=rp.SCHED_DIRECT_SUBMISSION)
# Register our callback with the UnitManager. This callback will get
# called every time any of the units managed by the UnitManager
# change their state.
umgr.register_callback(unit_state_cb)
# Add the previously created ComputePilot to the UnitManager.
umgr.add_pilots(pilot)
# Submit the previously created ComputeUnit descriptions to the
# PilotManager. This will trigger the selected scheduler to start
# assigning ComputeUnits to the ComputePilots.
units = umgr.submit_units(cud_list)
# Wait for all compute units to reach a terminal state (DONE or FAILED).
umgr.wait_units()
if not isinstance(units, list):
units = [units]
for unit in units:
print "* Task %s - state: %s, exit code: %s, started: %s, finished: %s, stdout: %s" \
% (unit.uid, unit.state, unit.exit_code, unit.start_time, unit.stop_time, unit.stdout)
except Exception as e:
# Something unexpected happened in the pilot code above
print "caught Exception: %s" % e
raise
except (KeyboardInterrupt, SystemExit) as e:
# the callback called sys.exit(), and we can here catch the
# corresponding KeyboardInterrupt exception for shutdown. We also catch
# SystemExit (which gets raised if the main threads exits for some other
# reason).
print "need to exit now: %s" % e
finally:
# always clean up the session, no matter if we caught an exception or
# not.
print "closing session"
session.close ()
# the above is equivalent to
#
# session.close (cleanup=True, terminate=True)
#
# it will thus both clean out the session's database record, and kill
# all remaining pilots (none in our example).
#-------------------------------------------------------------------------------
<|fim▁end|> | session_name = None |
<|file_name|>running_mpi_executables.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
__copyright__ = "Copyright 2013-2014, http://radical.rutgers.edu"
__license__ = "MIT"
import sys
import radical.pilot as rp
# READ: The RADICAL-Pilot documentation:
# http://radicalpilot.readthedocs.org/en/latest
#
# Try running this example with RADICAL_PILOT_VERBOSE=debug set if
# you want to see what happens behind the scenes!
#------------------------------------------------------------------------------
#
def pilot_state_cb (pilot, state):
""" this callback is invoked on all pilot state changes """
print "[Callback]: ComputePilot '%s' state: %s." % (pilot.uid, state)
if state == rp.FAILED:
sys.exit (1)
#------------------------------------------------------------------------------
#
def unit_state_cb (unit, state):
""" this callback is invoked on all unit state changes """
print "[Callback]: ComputeUnit '%s' state: %s." % (unit.uid, state)
if state == rp.FAILED:
sys.exit (1)
# ------------------------------------------------------------------------------
#
if __name__ == "__main__":
# we can optionally pass session name to RP
if len(sys.argv) > 1:
session_name = sys.argv[1]
else:
session_name = None
# Create a new session. No need to try/except this: if session creation
# fails, there is not much we can do anyways...
session = rp.Session(name=session_name)
print "session id: %s" % session.uid
# all other pilot code is now tried/excepted. If an exception is caught, we
# can rely on the session object to exist and be valid, and we can thus tear
# the whole RP stack down via a 'session.close()' call in the 'finally'
# clause...
try:
# Add a Pilot Manager. Pilot managers manage one or more ComputePilots.
pmgr = rp.PilotManager(session=session)
# Register our callback with the PilotManager. This callback will get
# called every time any of the pilots managed by the PilotManager
# change their state.
pmgr.register_callback(pilot_state_cb)
# Define a X-core on stamped that runs for N minutes and
# uses $HOME/radical.pilot.sandbox as sandbox directoy.
pdesc = rp.ComputePilotDescription()
pdesc.resource = "xsede.stampede"
pdesc.runtime = 15 # N minutes
pdesc.cores = 16 # X cores
pdesc.project = "TG-MCB090174"
# Launch the pilot.
pilot = pmgr.submit_pilots(pdesc)
cud_list = []
for unit_count in range(0, 4):
cu = rp.ComputeUnitDescription()
cu.pre_exec = ["module load python intel mvapich2 mpi4py"]
cu.executable = "python"
cu.arguments = ["helloworld_mpi.py"]
cu.input_staging = ["helloworld_mpi.py"]
# These two parameters are relevant to MPI execution:
# 'cores' sets the number of cores required by the task
# 'mpi' identifies the task as an MPI taskg
cu.cores = 8
cu.mpi = True
cud_list.append(cu)
# Combine the ComputePilot, the ComputeUnits and a scheduler via
# a UnitManager object.
umgr = rp.UnitManager(
session=session,
scheduler=rp.SCHED_DIRECT_SUBMISSION)
# Register our callback with the UnitManager. This callback will get
# called every time any of the units managed by the UnitManager
# change their state.
umgr.register_callback(unit_state_cb)
# Add the previously created ComputePilot to the UnitManager.
umgr.add_pilots(pilot)
# Submit the previously created ComputeUnit descriptions to the
# PilotManager. This will trigger the selected scheduler to start
# assigning ComputeUnits to the ComputePilots.
units = umgr.submit_units(cud_list)
# Wait for all compute units to reach a terminal state (DONE or FAILED).
umgr.wait_units()
if not isinstance(units, list):
<|fim_middle|>
for unit in units:
print "* Task %s - state: %s, exit code: %s, started: %s, finished: %s, stdout: %s" \
% (unit.uid, unit.state, unit.exit_code, unit.start_time, unit.stop_time, unit.stdout)
except Exception as e:
# Something unexpected happened in the pilot code above
print "caught Exception: %s" % e
raise
except (KeyboardInterrupt, SystemExit) as e:
# the callback called sys.exit(), and we can here catch the
# corresponding KeyboardInterrupt exception for shutdown. We also catch
# SystemExit (which gets raised if the main threads exits for some other
# reason).
print "need to exit now: %s" % e
finally:
# always clean up the session, no matter if we caught an exception or
# not.
print "closing session"
session.close ()
# the above is equivalent to
#
# session.close (cleanup=True, terminate=True)
#
# it will thus both clean out the session's database record, and kill
# all remaining pilots (none in our example).
#-------------------------------------------------------------------------------
<|fim▁end|> | units = [units] |
<|file_name|>running_mpi_executables.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
__copyright__ = "Copyright 2013-2014, http://radical.rutgers.edu"
__license__ = "MIT"
import sys
import radical.pilot as rp
# READ: The RADICAL-Pilot documentation:
# http://radicalpilot.readthedocs.org/en/latest
#
# Try running this example with RADICAL_PILOT_VERBOSE=debug set if
# you want to see what happens behind the scenes!
#------------------------------------------------------------------------------
#
def <|fim_middle|> (pilot, state):
""" this callback is invoked on all pilot state changes """
print "[Callback]: ComputePilot '%s' state: %s." % (pilot.uid, state)
if state == rp.FAILED:
sys.exit (1)
#------------------------------------------------------------------------------
#
def unit_state_cb (unit, state):
""" this callback is invoked on all unit state changes """
print "[Callback]: ComputeUnit '%s' state: %s." % (unit.uid, state)
if state == rp.FAILED:
sys.exit (1)
# ------------------------------------------------------------------------------
#
if __name__ == "__main__":
# we can optionally pass session name to RP
if len(sys.argv) > 1:
session_name = sys.argv[1]
else:
session_name = None
# Create a new session. No need to try/except this: if session creation
# fails, there is not much we can do anyways...
session = rp.Session(name=session_name)
print "session id: %s" % session.uid
# all other pilot code is now tried/excepted. If an exception is caught, we
# can rely on the session object to exist and be valid, and we can thus tear
# the whole RP stack down via a 'session.close()' call in the 'finally'
# clause...
try:
# Add a Pilot Manager. Pilot managers manage one or more ComputePilots.
pmgr = rp.PilotManager(session=session)
# Register our callback with the PilotManager. This callback will get
# called every time any of the pilots managed by the PilotManager
# change their state.
pmgr.register_callback(pilot_state_cb)
# Define a X-core on stamped that runs for N minutes and
# uses $HOME/radical.pilot.sandbox as sandbox directoy.
pdesc = rp.ComputePilotDescription()
pdesc.resource = "xsede.stampede"
pdesc.runtime = 15 # N minutes
pdesc.cores = 16 # X cores
pdesc.project = "TG-MCB090174"
# Launch the pilot.
pilot = pmgr.submit_pilots(pdesc)
cud_list = []
for unit_count in range(0, 4):
cu = rp.ComputeUnitDescription()
cu.pre_exec = ["module load python intel mvapich2 mpi4py"]
cu.executable = "python"
cu.arguments = ["helloworld_mpi.py"]
cu.input_staging = ["helloworld_mpi.py"]
# These two parameters are relevant to MPI execution:
# 'cores' sets the number of cores required by the task
# 'mpi' identifies the task as an MPI taskg
cu.cores = 8
cu.mpi = True
cud_list.append(cu)
# Combine the ComputePilot, the ComputeUnits and a scheduler via
# a UnitManager object.
umgr = rp.UnitManager(
session=session,
scheduler=rp.SCHED_DIRECT_SUBMISSION)
# Register our callback with the UnitManager. This callback will get
# called every time any of the units managed by the UnitManager
# change their state.
umgr.register_callback(unit_state_cb)
# Add the previously created ComputePilot to the UnitManager.
umgr.add_pilots(pilot)
# Submit the previously created ComputeUnit descriptions to the
# PilotManager. This will trigger the selected scheduler to start
# assigning ComputeUnits to the ComputePilots.
units = umgr.submit_units(cud_list)
# Wait for all compute units to reach a terminal state (DONE or FAILED).
umgr.wait_units()
if not isinstance(units, list):
units = [units]
for unit in units:
print "* Task %s - state: %s, exit code: %s, started: %s, finished: %s, stdout: %s" \
% (unit.uid, unit.state, unit.exit_code, unit.start_time, unit.stop_time, unit.stdout)
except Exception as e:
# Something unexpected happened in the pilot code above
print "caught Exception: %s" % e
raise
except (KeyboardInterrupt, SystemExit) as e:
# the callback called sys.exit(), and we can here catch the
# corresponding KeyboardInterrupt exception for shutdown. We also catch
# SystemExit (which gets raised if the main threads exits for some other
# reason).
print "need to exit now: %s" % e
finally:
# always clean up the session, no matter if we caught an exception or
# not.
print "closing session"
session.close ()
# the above is equivalent to
#
# session.close (cleanup=True, terminate=True)
#
# it will thus both clean out the session's database record, and kill
# all remaining pilots (none in our example).
#-------------------------------------------------------------------------------
<|fim▁end|> | pilot_state_cb |
<|file_name|>running_mpi_executables.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
__copyright__ = "Copyright 2013-2014, http://radical.rutgers.edu"
__license__ = "MIT"
import sys
import radical.pilot as rp
# READ: The RADICAL-Pilot documentation:
# http://radicalpilot.readthedocs.org/en/latest
#
# Try running this example with RADICAL_PILOT_VERBOSE=debug set if
# you want to see what happens behind the scenes!
#------------------------------------------------------------------------------
#
def pilot_state_cb (pilot, state):
""" this callback is invoked on all pilot state changes """
print "[Callback]: ComputePilot '%s' state: %s." % (pilot.uid, state)
if state == rp.FAILED:
sys.exit (1)
#------------------------------------------------------------------------------
#
def <|fim_middle|> (unit, state):
""" this callback is invoked on all unit state changes """
print "[Callback]: ComputeUnit '%s' state: %s." % (unit.uid, state)
if state == rp.FAILED:
sys.exit (1)
# ------------------------------------------------------------------------------
#
if __name__ == "__main__":
# we can optionally pass session name to RP
if len(sys.argv) > 1:
session_name = sys.argv[1]
else:
session_name = None
# Create a new session. No need to try/except this: if session creation
# fails, there is not much we can do anyways...
session = rp.Session(name=session_name)
print "session id: %s" % session.uid
# all other pilot code is now tried/excepted. If an exception is caught, we
# can rely on the session object to exist and be valid, and we can thus tear
# the whole RP stack down via a 'session.close()' call in the 'finally'
# clause...
try:
# Add a Pilot Manager. Pilot managers manage one or more ComputePilots.
pmgr = rp.PilotManager(session=session)
# Register our callback with the PilotManager. This callback will get
# called every time any of the pilots managed by the PilotManager
# change their state.
pmgr.register_callback(pilot_state_cb)
# Define a X-core on stamped that runs for N minutes and
# uses $HOME/radical.pilot.sandbox as sandbox directoy.
pdesc = rp.ComputePilotDescription()
pdesc.resource = "xsede.stampede"
pdesc.runtime = 15 # N minutes
pdesc.cores = 16 # X cores
pdesc.project = "TG-MCB090174"
# Launch the pilot.
pilot = pmgr.submit_pilots(pdesc)
cud_list = []
for unit_count in range(0, 4):
cu = rp.ComputeUnitDescription()
cu.pre_exec = ["module load python intel mvapich2 mpi4py"]
cu.executable = "python"
cu.arguments = ["helloworld_mpi.py"]
cu.input_staging = ["helloworld_mpi.py"]
# These two parameters are relevant to MPI execution:
# 'cores' sets the number of cores required by the task
# 'mpi' identifies the task as an MPI taskg
cu.cores = 8
cu.mpi = True
cud_list.append(cu)
# Combine the ComputePilot, the ComputeUnits and a scheduler via
# a UnitManager object.
umgr = rp.UnitManager(
session=session,
scheduler=rp.SCHED_DIRECT_SUBMISSION)
# Register our callback with the UnitManager. This callback will get
# called every time any of the units managed by the UnitManager
# change their state.
umgr.register_callback(unit_state_cb)
# Add the previously created ComputePilot to the UnitManager.
umgr.add_pilots(pilot)
# Submit the previously created ComputeUnit descriptions to the
# PilotManager. This will trigger the selected scheduler to start
# assigning ComputeUnits to the ComputePilots.
units = umgr.submit_units(cud_list)
# Wait for all compute units to reach a terminal state (DONE or FAILED).
umgr.wait_units()
if not isinstance(units, list):
units = [units]
for unit in units:
print "* Task %s - state: %s, exit code: %s, started: %s, finished: %s, stdout: %s" \
% (unit.uid, unit.state, unit.exit_code, unit.start_time, unit.stop_time, unit.stdout)
except Exception as e:
# Something unexpected happened in the pilot code above
print "caught Exception: %s" % e
raise
except (KeyboardInterrupt, SystemExit) as e:
# the callback called sys.exit(), and we can here catch the
# corresponding KeyboardInterrupt exception for shutdown. We also catch
# SystemExit (which gets raised if the main threads exits for some other
# reason).
print "need to exit now: %s" % e
finally:
# always clean up the session, no matter if we caught an exception or
# not.
print "closing session"
session.close ()
# the above is equivalent to
#
# session.close (cleanup=True, terminate=True)
#
# it will thus both clean out the session's database record, and kill
# all remaining pilots (none in our example).
#-------------------------------------------------------------------------------
<|fim▁end|> | unit_state_cb |
<|file_name|>test_reference_bind.py<|end_file_name|><|fim▁begin|># Copyright 2017 Virgil Dupras
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
from datetime import date
from itertools import starmap
from hscommon.testutil import eq_
from ...model.amount import Amount
from ...model.currency import USD
from ...model.entry import Entry
from ...model.transaction import Transaction
from ...plugin.base_import_bind import ReferenceBind
def create_entry(entry_date, description, reference):
txn = Transaction(entry_date, description=description, amount=Amount(1, USD))
split = txn.splits[0]
split.reference = reference
return Entry(split, split.amount, 0, 0, 0)<|fim▁hole|> # We only match entries with the same reference
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing_entries = list(starmap(create_entry, [
(DATE, 'e1', 'ref1'),
(DATE, 'e2', 'ref2'),
]))
imported_entries = list(starmap(create_entry, [
(DATE, 'i1', 'ref1'),
(DATE, 'i2', 'ref3'),
]))
matches = plugin.match_entries(None, None, None, existing_entries, imported_entries)
EXPECTED = [('e1', 'i1', True, 0.99)]
result = [(m.existing.description, m.imported.description, m.will_import, m.weight) for m in matches]
eq_(result, EXPECTED)
def test_reconciled_entry():
# Reconciled entries are matched, but with will_import = False
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing = create_entry(DATE, 'e1', 'ref1')
existing.split.reconciliation_date = DATE
imported = create_entry(DATE, 'i1', 'ref1')
matches = plugin.match_entries(None, None, None, [existing], [imported])
EXPECTED = [('e1', 'i1', False, 0.99)]
result = [(m.existing.description, m.imported.description, m.will_import, m.weight) for m in matches]
eq_(result, EXPECTED)
def test_match_first_only():
# If two entries have the same reference, we only get one match (we don't care which, it's not
# really supposed to happen...).
# Verify that ReferenceBind.match_entries() return expected entried in a typical situation
# We only match entries with the same reference
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing_entries = list(starmap(create_entry, [
(DATE, 'e1', 'ref1'),
]))
imported_entries = list(starmap(create_entry, [
(DATE, 'i1', 'ref1'),
(DATE, 'i2', 'ref1'),
]))
matches = plugin.match_entries(None, None, None, existing_entries, imported_entries)
eq_(len(matches), 1)<|fim▁end|> |
def test_typical_situation():
# Verify that ReferenceBind.match_entries() return expected entried in a typical situation |
<|file_name|>test_reference_bind.py<|end_file_name|><|fim▁begin|># Copyright 2017 Virgil Dupras
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
from datetime import date
from itertools import starmap
from hscommon.testutil import eq_
from ...model.amount import Amount
from ...model.currency import USD
from ...model.entry import Entry
from ...model.transaction import Transaction
from ...plugin.base_import_bind import ReferenceBind
def create_entry(entry_date, description, reference):
<|fim_middle|>
def test_typical_situation():
# Verify that ReferenceBind.match_entries() return expected entried in a typical situation
# We only match entries with the same reference
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing_entries = list(starmap(create_entry, [
(DATE, 'e1', 'ref1'),
(DATE, 'e2', 'ref2'),
]))
imported_entries = list(starmap(create_entry, [
(DATE, 'i1', 'ref1'),
(DATE, 'i2', 'ref3'),
]))
matches = plugin.match_entries(None, None, None, existing_entries, imported_entries)
EXPECTED = [('e1', 'i1', True, 0.99)]
result = [(m.existing.description, m.imported.description, m.will_import, m.weight) for m in matches]
eq_(result, EXPECTED)
def test_reconciled_entry():
# Reconciled entries are matched, but with will_import = False
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing = create_entry(DATE, 'e1', 'ref1')
existing.split.reconciliation_date = DATE
imported = create_entry(DATE, 'i1', 'ref1')
matches = plugin.match_entries(None, None, None, [existing], [imported])
EXPECTED = [('e1', 'i1', False, 0.99)]
result = [(m.existing.description, m.imported.description, m.will_import, m.weight) for m in matches]
eq_(result, EXPECTED)
def test_match_first_only():
# If two entries have the same reference, we only get one match (we don't care which, it's not
# really supposed to happen...).
# Verify that ReferenceBind.match_entries() return expected entried in a typical situation
# We only match entries with the same reference
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing_entries = list(starmap(create_entry, [
(DATE, 'e1', 'ref1'),
]))
imported_entries = list(starmap(create_entry, [
(DATE, 'i1', 'ref1'),
(DATE, 'i2', 'ref1'),
]))
matches = plugin.match_entries(None, None, None, existing_entries, imported_entries)
eq_(len(matches), 1)
<|fim▁end|> | txn = Transaction(entry_date, description=description, amount=Amount(1, USD))
split = txn.splits[0]
split.reference = reference
return Entry(split, split.amount, 0, 0, 0) |
<|file_name|>test_reference_bind.py<|end_file_name|><|fim▁begin|># Copyright 2017 Virgil Dupras
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
from datetime import date
from itertools import starmap
from hscommon.testutil import eq_
from ...model.amount import Amount
from ...model.currency import USD
from ...model.entry import Entry
from ...model.transaction import Transaction
from ...plugin.base_import_bind import ReferenceBind
def create_entry(entry_date, description, reference):
txn = Transaction(entry_date, description=description, amount=Amount(1, USD))
split = txn.splits[0]
split.reference = reference
return Entry(split, split.amount, 0, 0, 0)
def test_typical_situation():
# Verify that ReferenceBind.match_entries() return expected entried in a typical situation
# We only match entries with the same reference
<|fim_middle|>
def test_reconciled_entry():
# Reconciled entries are matched, but with will_import = False
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing = create_entry(DATE, 'e1', 'ref1')
existing.split.reconciliation_date = DATE
imported = create_entry(DATE, 'i1', 'ref1')
matches = plugin.match_entries(None, None, None, [existing], [imported])
EXPECTED = [('e1', 'i1', False, 0.99)]
result = [(m.existing.description, m.imported.description, m.will_import, m.weight) for m in matches]
eq_(result, EXPECTED)
def test_match_first_only():
# If two entries have the same reference, we only get one match (we don't care which, it's not
# really supposed to happen...).
# Verify that ReferenceBind.match_entries() return expected entried in a typical situation
# We only match entries with the same reference
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing_entries = list(starmap(create_entry, [
(DATE, 'e1', 'ref1'),
]))
imported_entries = list(starmap(create_entry, [
(DATE, 'i1', 'ref1'),
(DATE, 'i2', 'ref1'),
]))
matches = plugin.match_entries(None, None, None, existing_entries, imported_entries)
eq_(len(matches), 1)
<|fim▁end|> | plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing_entries = list(starmap(create_entry, [
(DATE, 'e1', 'ref1'),
(DATE, 'e2', 'ref2'),
]))
imported_entries = list(starmap(create_entry, [
(DATE, 'i1', 'ref1'),
(DATE, 'i2', 'ref3'),
]))
matches = plugin.match_entries(None, None, None, existing_entries, imported_entries)
EXPECTED = [('e1', 'i1', True, 0.99)]
result = [(m.existing.description, m.imported.description, m.will_import, m.weight) for m in matches]
eq_(result, EXPECTED) |
<|file_name|>test_reference_bind.py<|end_file_name|><|fim▁begin|># Copyright 2017 Virgil Dupras
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
from datetime import date
from itertools import starmap
from hscommon.testutil import eq_
from ...model.amount import Amount
from ...model.currency import USD
from ...model.entry import Entry
from ...model.transaction import Transaction
from ...plugin.base_import_bind import ReferenceBind
def create_entry(entry_date, description, reference):
txn = Transaction(entry_date, description=description, amount=Amount(1, USD))
split = txn.splits[0]
split.reference = reference
return Entry(split, split.amount, 0, 0, 0)
def test_typical_situation():
# Verify that ReferenceBind.match_entries() return expected entried in a typical situation
# We only match entries with the same reference
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing_entries = list(starmap(create_entry, [
(DATE, 'e1', 'ref1'),
(DATE, 'e2', 'ref2'),
]))
imported_entries = list(starmap(create_entry, [
(DATE, 'i1', 'ref1'),
(DATE, 'i2', 'ref3'),
]))
matches = plugin.match_entries(None, None, None, existing_entries, imported_entries)
EXPECTED = [('e1', 'i1', True, 0.99)]
result = [(m.existing.description, m.imported.description, m.will_import, m.weight) for m in matches]
eq_(result, EXPECTED)
def test_reconciled_entry():
# Reconciled entries are matched, but with will_import = False
<|fim_middle|>
def test_match_first_only():
# If two entries have the same reference, we only get one match (we don't care which, it's not
# really supposed to happen...).
# Verify that ReferenceBind.match_entries() return expected entried in a typical situation
# We only match entries with the same reference
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing_entries = list(starmap(create_entry, [
(DATE, 'e1', 'ref1'),
]))
imported_entries = list(starmap(create_entry, [
(DATE, 'i1', 'ref1'),
(DATE, 'i2', 'ref1'),
]))
matches = plugin.match_entries(None, None, None, existing_entries, imported_entries)
eq_(len(matches), 1)
<|fim▁end|> | plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing = create_entry(DATE, 'e1', 'ref1')
existing.split.reconciliation_date = DATE
imported = create_entry(DATE, 'i1', 'ref1')
matches = plugin.match_entries(None, None, None, [existing], [imported])
EXPECTED = [('e1', 'i1', False, 0.99)]
result = [(m.existing.description, m.imported.description, m.will_import, m.weight) for m in matches]
eq_(result, EXPECTED) |
<|file_name|>test_reference_bind.py<|end_file_name|><|fim▁begin|># Copyright 2017 Virgil Dupras
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
from datetime import date
from itertools import starmap
from hscommon.testutil import eq_
from ...model.amount import Amount
from ...model.currency import USD
from ...model.entry import Entry
from ...model.transaction import Transaction
from ...plugin.base_import_bind import ReferenceBind
def create_entry(entry_date, description, reference):
txn = Transaction(entry_date, description=description, amount=Amount(1, USD))
split = txn.splits[0]
split.reference = reference
return Entry(split, split.amount, 0, 0, 0)
def test_typical_situation():
# Verify that ReferenceBind.match_entries() return expected entried in a typical situation
# We only match entries with the same reference
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing_entries = list(starmap(create_entry, [
(DATE, 'e1', 'ref1'),
(DATE, 'e2', 'ref2'),
]))
imported_entries = list(starmap(create_entry, [
(DATE, 'i1', 'ref1'),
(DATE, 'i2', 'ref3'),
]))
matches = plugin.match_entries(None, None, None, existing_entries, imported_entries)
EXPECTED = [('e1', 'i1', True, 0.99)]
result = [(m.existing.description, m.imported.description, m.will_import, m.weight) for m in matches]
eq_(result, EXPECTED)
def test_reconciled_entry():
# Reconciled entries are matched, but with will_import = False
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing = create_entry(DATE, 'e1', 'ref1')
existing.split.reconciliation_date = DATE
imported = create_entry(DATE, 'i1', 'ref1')
matches = plugin.match_entries(None, None, None, [existing], [imported])
EXPECTED = [('e1', 'i1', False, 0.99)]
result = [(m.existing.description, m.imported.description, m.will_import, m.weight) for m in matches]
eq_(result, EXPECTED)
def test_match_first_only():
# If two entries have the same reference, we only get one match (we don't care which, it's not
# really supposed to happen...).
# Verify that ReferenceBind.match_entries() return expected entried in a typical situation
# We only match entries with the same reference
<|fim_middle|>
<|fim▁end|> | plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing_entries = list(starmap(create_entry, [
(DATE, 'e1', 'ref1'),
]))
imported_entries = list(starmap(create_entry, [
(DATE, 'i1', 'ref1'),
(DATE, 'i2', 'ref1'),
]))
matches = plugin.match_entries(None, None, None, existing_entries, imported_entries)
eq_(len(matches), 1) |
<|file_name|>test_reference_bind.py<|end_file_name|><|fim▁begin|># Copyright 2017 Virgil Dupras
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
from datetime import date
from itertools import starmap
from hscommon.testutil import eq_
from ...model.amount import Amount
from ...model.currency import USD
from ...model.entry import Entry
from ...model.transaction import Transaction
from ...plugin.base_import_bind import ReferenceBind
def <|fim_middle|>(entry_date, description, reference):
txn = Transaction(entry_date, description=description, amount=Amount(1, USD))
split = txn.splits[0]
split.reference = reference
return Entry(split, split.amount, 0, 0, 0)
def test_typical_situation():
# Verify that ReferenceBind.match_entries() return expected entried in a typical situation
# We only match entries with the same reference
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing_entries = list(starmap(create_entry, [
(DATE, 'e1', 'ref1'),
(DATE, 'e2', 'ref2'),
]))
imported_entries = list(starmap(create_entry, [
(DATE, 'i1', 'ref1'),
(DATE, 'i2', 'ref3'),
]))
matches = plugin.match_entries(None, None, None, existing_entries, imported_entries)
EXPECTED = [('e1', 'i1', True, 0.99)]
result = [(m.existing.description, m.imported.description, m.will_import, m.weight) for m in matches]
eq_(result, EXPECTED)
def test_reconciled_entry():
# Reconciled entries are matched, but with will_import = False
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing = create_entry(DATE, 'e1', 'ref1')
existing.split.reconciliation_date = DATE
imported = create_entry(DATE, 'i1', 'ref1')
matches = plugin.match_entries(None, None, None, [existing], [imported])
EXPECTED = [('e1', 'i1', False, 0.99)]
result = [(m.existing.description, m.imported.description, m.will_import, m.weight) for m in matches]
eq_(result, EXPECTED)
def test_match_first_only():
# If two entries have the same reference, we only get one match (we don't care which, it's not
# really supposed to happen...).
# Verify that ReferenceBind.match_entries() return expected entried in a typical situation
# We only match entries with the same reference
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing_entries = list(starmap(create_entry, [
(DATE, 'e1', 'ref1'),
]))
imported_entries = list(starmap(create_entry, [
(DATE, 'i1', 'ref1'),
(DATE, 'i2', 'ref1'),
]))
matches = plugin.match_entries(None, None, None, existing_entries, imported_entries)
eq_(len(matches), 1)
<|fim▁end|> | create_entry |
<|file_name|>test_reference_bind.py<|end_file_name|><|fim▁begin|># Copyright 2017 Virgil Dupras
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
from datetime import date
from itertools import starmap
from hscommon.testutil import eq_
from ...model.amount import Amount
from ...model.currency import USD
from ...model.entry import Entry
from ...model.transaction import Transaction
from ...plugin.base_import_bind import ReferenceBind
def create_entry(entry_date, description, reference):
txn = Transaction(entry_date, description=description, amount=Amount(1, USD))
split = txn.splits[0]
split.reference = reference
return Entry(split, split.amount, 0, 0, 0)
def <|fim_middle|>():
# Verify that ReferenceBind.match_entries() return expected entried in a typical situation
# We only match entries with the same reference
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing_entries = list(starmap(create_entry, [
(DATE, 'e1', 'ref1'),
(DATE, 'e2', 'ref2'),
]))
imported_entries = list(starmap(create_entry, [
(DATE, 'i1', 'ref1'),
(DATE, 'i2', 'ref3'),
]))
matches = plugin.match_entries(None, None, None, existing_entries, imported_entries)
EXPECTED = [('e1', 'i1', True, 0.99)]
result = [(m.existing.description, m.imported.description, m.will_import, m.weight) for m in matches]
eq_(result, EXPECTED)
def test_reconciled_entry():
# Reconciled entries are matched, but with will_import = False
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing = create_entry(DATE, 'e1', 'ref1')
existing.split.reconciliation_date = DATE
imported = create_entry(DATE, 'i1', 'ref1')
matches = plugin.match_entries(None, None, None, [existing], [imported])
EXPECTED = [('e1', 'i1', False, 0.99)]
result = [(m.existing.description, m.imported.description, m.will_import, m.weight) for m in matches]
eq_(result, EXPECTED)
def test_match_first_only():
# If two entries have the same reference, we only get one match (we don't care which, it's not
# really supposed to happen...).
# Verify that ReferenceBind.match_entries() return expected entried in a typical situation
# We only match entries with the same reference
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing_entries = list(starmap(create_entry, [
(DATE, 'e1', 'ref1'),
]))
imported_entries = list(starmap(create_entry, [
(DATE, 'i1', 'ref1'),
(DATE, 'i2', 'ref1'),
]))
matches = plugin.match_entries(None, None, None, existing_entries, imported_entries)
eq_(len(matches), 1)
<|fim▁end|> | test_typical_situation |
<|file_name|>test_reference_bind.py<|end_file_name|><|fim▁begin|># Copyright 2017 Virgil Dupras
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
from datetime import date
from itertools import starmap
from hscommon.testutil import eq_
from ...model.amount import Amount
from ...model.currency import USD
from ...model.entry import Entry
from ...model.transaction import Transaction
from ...plugin.base_import_bind import ReferenceBind
def create_entry(entry_date, description, reference):
txn = Transaction(entry_date, description=description, amount=Amount(1, USD))
split = txn.splits[0]
split.reference = reference
return Entry(split, split.amount, 0, 0, 0)
def test_typical_situation():
# Verify that ReferenceBind.match_entries() return expected entried in a typical situation
# We only match entries with the same reference
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing_entries = list(starmap(create_entry, [
(DATE, 'e1', 'ref1'),
(DATE, 'e2', 'ref2'),
]))
imported_entries = list(starmap(create_entry, [
(DATE, 'i1', 'ref1'),
(DATE, 'i2', 'ref3'),
]))
matches = plugin.match_entries(None, None, None, existing_entries, imported_entries)
EXPECTED = [('e1', 'i1', True, 0.99)]
result = [(m.existing.description, m.imported.description, m.will_import, m.weight) for m in matches]
eq_(result, EXPECTED)
def <|fim_middle|>():
# Reconciled entries are matched, but with will_import = False
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing = create_entry(DATE, 'e1', 'ref1')
existing.split.reconciliation_date = DATE
imported = create_entry(DATE, 'i1', 'ref1')
matches = plugin.match_entries(None, None, None, [existing], [imported])
EXPECTED = [('e1', 'i1', False, 0.99)]
result = [(m.existing.description, m.imported.description, m.will_import, m.weight) for m in matches]
eq_(result, EXPECTED)
def test_match_first_only():
# If two entries have the same reference, we only get one match (we don't care which, it's not
# really supposed to happen...).
# Verify that ReferenceBind.match_entries() return expected entried in a typical situation
# We only match entries with the same reference
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing_entries = list(starmap(create_entry, [
(DATE, 'e1', 'ref1'),
]))
imported_entries = list(starmap(create_entry, [
(DATE, 'i1', 'ref1'),
(DATE, 'i2', 'ref1'),
]))
matches = plugin.match_entries(None, None, None, existing_entries, imported_entries)
eq_(len(matches), 1)
<|fim▁end|> | test_reconciled_entry |
<|file_name|>test_reference_bind.py<|end_file_name|><|fim▁begin|># Copyright 2017 Virgil Dupras
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
from datetime import date
from itertools import starmap
from hscommon.testutil import eq_
from ...model.amount import Amount
from ...model.currency import USD
from ...model.entry import Entry
from ...model.transaction import Transaction
from ...plugin.base_import_bind import ReferenceBind
def create_entry(entry_date, description, reference):
txn = Transaction(entry_date, description=description, amount=Amount(1, USD))
split = txn.splits[0]
split.reference = reference
return Entry(split, split.amount, 0, 0, 0)
def test_typical_situation():
# Verify that ReferenceBind.match_entries() return expected entried in a typical situation
# We only match entries with the same reference
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing_entries = list(starmap(create_entry, [
(DATE, 'e1', 'ref1'),
(DATE, 'e2', 'ref2'),
]))
imported_entries = list(starmap(create_entry, [
(DATE, 'i1', 'ref1'),
(DATE, 'i2', 'ref3'),
]))
matches = plugin.match_entries(None, None, None, existing_entries, imported_entries)
EXPECTED = [('e1', 'i1', True, 0.99)]
result = [(m.existing.description, m.imported.description, m.will_import, m.weight) for m in matches]
eq_(result, EXPECTED)
def test_reconciled_entry():
# Reconciled entries are matched, but with will_import = False
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing = create_entry(DATE, 'e1', 'ref1')
existing.split.reconciliation_date = DATE
imported = create_entry(DATE, 'i1', 'ref1')
matches = plugin.match_entries(None, None, None, [existing], [imported])
EXPECTED = [('e1', 'i1', False, 0.99)]
result = [(m.existing.description, m.imported.description, m.will_import, m.weight) for m in matches]
eq_(result, EXPECTED)
def <|fim_middle|>():
# If two entries have the same reference, we only get one match (we don't care which, it's not
# really supposed to happen...).
# Verify that ReferenceBind.match_entries() return expected entried in a typical situation
# We only match entries with the same reference
plugin = ReferenceBind()
DATE = date(2017, 10, 10)
existing_entries = list(starmap(create_entry, [
(DATE, 'e1', 'ref1'),
]))
imported_entries = list(starmap(create_entry, [
(DATE, 'i1', 'ref1'),
(DATE, 'i2', 'ref1'),
]))
matches = plugin.match_entries(None, None, None, existing_entries, imported_entries)
eq_(len(matches), 1)
<|fim▁end|> | test_match_first_only |
<|file_name|>fm_demod.py<|end_file_name|><|fim▁begin|>#
# Copyright 2006,2007 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr, optfir
from gnuradio.blks2impl.fm_emph import fm_deemph
from math import pi
class fm_demod_cf(gr.hier_block2):
"""
Generalized FM demodulation block with deemphasis and audio
filtering.
This block demodulates a band-limited, complex down-converted FM
channel into the the original baseband signal, optionally applying
deemphasis. Low pass filtering is done on the resultant signal. It
produces an output float strem in the range of [-1.0, +1.0].
@param channel_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param deviation: maximum FM deviation (default = 5000)
@type deviation: float
@param audio_decim: input to output decimation rate
@type audio_decim: integer
@param audio_pass: audio low pass filter passband frequency
@type audio_pass: float
@param audio_stop: audio low pass filter stop frequency
@type audio_stop: float
@param gain: gain applied to audio output (default = 1.0)
@type gain: float
@param tau: deemphasis time constant (default = 75e-6), specify 'None'
to prevent deemphasis
"""
def __init__(self, channel_rate, audio_decim, deviation,
audio_pass, audio_stop, gain=1.0, tau=75e-6):
gr.hier_block2.__init__(self, "fm_demod_cf",
gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
gr.io_signature(1, 1, gr.sizeof_float)) # Output signature
k = channel_rate/(2*pi*deviation)
QUAD = gr.quadrature_demod_cf(k)
audio_taps = optfir.low_pass(gain, # Filter gain
channel_rate, # Sample rate
audio_pass, # Audio passband
audio_stop, # Audio stopband
0.1, # Passband ripple
60) # Stopband attenuation
LPF = gr.fir_filter_fff(audio_decim, audio_taps)
if tau is not None:
DEEMPH = fm_deemph(channel_rate, tau)
self.connect(self, QUAD, DEEMPH, LPF, self)
else:
self.connect(self, QUAD, LPF, self)
class demod_20k0f3e_cf(fm_demod_cf):
"""
NBFM demodulation block, 20 KHz channels
This block demodulates a complex, downconverted, narrowband FM
channel conforming to 20K0F3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband<|fim▁hole|> def __init__(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
5000, # Deviation
3000, # Audio passband frequency
4500) # Audio stopband frequency
class demod_200kf3e_cf(fm_demod_cf):
"""
WFM demodulation block, mono.
This block demodulates a complex, downconverted, wideband FM
channel conforming to 200KF3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
75000, # Deviation
15000, # Audio passband
16000, # Audio stopband
20.0) # Audio gain<|fim▁end|> | @type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
""" |
<|file_name|>fm_demod.py<|end_file_name|><|fim▁begin|>#
# Copyright 2006,2007 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr, optfir
from gnuradio.blks2impl.fm_emph import fm_deemph
from math import pi
class fm_demod_cf(gr.hier_block2):
<|fim_middle|>
class demod_20k0f3e_cf(fm_demod_cf):
"""
NBFM demodulation block, 20 KHz channels
This block demodulates a complex, downconverted, narrowband FM
channel conforming to 20K0F3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
5000, # Deviation
3000, # Audio passband frequency
4500) # Audio stopband frequency
class demod_200kf3e_cf(fm_demod_cf):
"""
WFM demodulation block, mono.
This block demodulates a complex, downconverted, wideband FM
channel conforming to 200KF3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
75000, # Deviation
15000, # Audio passband
16000, # Audio stopband
20.0) # Audio gain
<|fim▁end|> | """
Generalized FM demodulation block with deemphasis and audio
filtering.
This block demodulates a band-limited, complex down-converted FM
channel into the the original baseband signal, optionally applying
deemphasis. Low pass filtering is done on the resultant signal. It
produces an output float strem in the range of [-1.0, +1.0].
@param channel_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param deviation: maximum FM deviation (default = 5000)
@type deviation: float
@param audio_decim: input to output decimation rate
@type audio_decim: integer
@param audio_pass: audio low pass filter passband frequency
@type audio_pass: float
@param audio_stop: audio low pass filter stop frequency
@type audio_stop: float
@param gain: gain applied to audio output (default = 1.0)
@type gain: float
@param tau: deemphasis time constant (default = 75e-6), specify 'None'
to prevent deemphasis
"""
def __init__(self, channel_rate, audio_decim, deviation,
audio_pass, audio_stop, gain=1.0, tau=75e-6):
gr.hier_block2.__init__(self, "fm_demod_cf",
gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
gr.io_signature(1, 1, gr.sizeof_float)) # Output signature
k = channel_rate/(2*pi*deviation)
QUAD = gr.quadrature_demod_cf(k)
audio_taps = optfir.low_pass(gain, # Filter gain
channel_rate, # Sample rate
audio_pass, # Audio passband
audio_stop, # Audio stopband
0.1, # Passband ripple
60) # Stopband attenuation
LPF = gr.fir_filter_fff(audio_decim, audio_taps)
if tau is not None:
DEEMPH = fm_deemph(channel_rate, tau)
self.connect(self, QUAD, DEEMPH, LPF, self)
else:
self.connect(self, QUAD, LPF, self) |
<|file_name|>fm_demod.py<|end_file_name|><|fim▁begin|>#
# Copyright 2006,2007 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr, optfir
from gnuradio.blks2impl.fm_emph import fm_deemph
from math import pi
class fm_demod_cf(gr.hier_block2):
"""
Generalized FM demodulation block with deemphasis and audio
filtering.
This block demodulates a band-limited, complex down-converted FM
channel into the the original baseband signal, optionally applying
deemphasis. Low pass filtering is done on the resultant signal. It
produces an output float strem in the range of [-1.0, +1.0].
@param channel_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param deviation: maximum FM deviation (default = 5000)
@type deviation: float
@param audio_decim: input to output decimation rate
@type audio_decim: integer
@param audio_pass: audio low pass filter passband frequency
@type audio_pass: float
@param audio_stop: audio low pass filter stop frequency
@type audio_stop: float
@param gain: gain applied to audio output (default = 1.0)
@type gain: float
@param tau: deemphasis time constant (default = 75e-6), specify 'None'
to prevent deemphasis
"""
def __init__(self, channel_rate, audio_decim, deviation,
audio_pass, audio_stop, gain=1.0, tau=75e-6):
<|fim_middle|>
class demod_20k0f3e_cf(fm_demod_cf):
"""
NBFM demodulation block, 20 KHz channels
This block demodulates a complex, downconverted, narrowband FM
channel conforming to 20K0F3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
5000, # Deviation
3000, # Audio passband frequency
4500) # Audio stopband frequency
class demod_200kf3e_cf(fm_demod_cf):
"""
WFM demodulation block, mono.
This block demodulates a complex, downconverted, wideband FM
channel conforming to 200KF3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
75000, # Deviation
15000, # Audio passband
16000, # Audio stopband
20.0) # Audio gain
<|fim▁end|> | gr.hier_block2.__init__(self, "fm_demod_cf",
gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
gr.io_signature(1, 1, gr.sizeof_float)) # Output signature
k = channel_rate/(2*pi*deviation)
QUAD = gr.quadrature_demod_cf(k)
audio_taps = optfir.low_pass(gain, # Filter gain
channel_rate, # Sample rate
audio_pass, # Audio passband
audio_stop, # Audio stopband
0.1, # Passband ripple
60) # Stopband attenuation
LPF = gr.fir_filter_fff(audio_decim, audio_taps)
if tau is not None:
DEEMPH = fm_deemph(channel_rate, tau)
self.connect(self, QUAD, DEEMPH, LPF, self)
else:
self.connect(self, QUAD, LPF, self) |
<|file_name|>fm_demod.py<|end_file_name|><|fim▁begin|>#
# Copyright 2006,2007 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr, optfir
from gnuradio.blks2impl.fm_emph import fm_deemph
from math import pi
class fm_demod_cf(gr.hier_block2):
"""
Generalized FM demodulation block with deemphasis and audio
filtering.
This block demodulates a band-limited, complex down-converted FM
channel into the the original baseband signal, optionally applying
deemphasis. Low pass filtering is done on the resultant signal. It
produces an output float strem in the range of [-1.0, +1.0].
@param channel_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param deviation: maximum FM deviation (default = 5000)
@type deviation: float
@param audio_decim: input to output decimation rate
@type audio_decim: integer
@param audio_pass: audio low pass filter passband frequency
@type audio_pass: float
@param audio_stop: audio low pass filter stop frequency
@type audio_stop: float
@param gain: gain applied to audio output (default = 1.0)
@type gain: float
@param tau: deemphasis time constant (default = 75e-6), specify 'None'
to prevent deemphasis
"""
def __init__(self, channel_rate, audio_decim, deviation,
audio_pass, audio_stop, gain=1.0, tau=75e-6):
gr.hier_block2.__init__(self, "fm_demod_cf",
gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
gr.io_signature(1, 1, gr.sizeof_float)) # Output signature
k = channel_rate/(2*pi*deviation)
QUAD = gr.quadrature_demod_cf(k)
audio_taps = optfir.low_pass(gain, # Filter gain
channel_rate, # Sample rate
audio_pass, # Audio passband
audio_stop, # Audio stopband
0.1, # Passband ripple
60) # Stopband attenuation
LPF = gr.fir_filter_fff(audio_decim, audio_taps)
if tau is not None:
DEEMPH = fm_deemph(channel_rate, tau)
self.connect(self, QUAD, DEEMPH, LPF, self)
else:
self.connect(self, QUAD, LPF, self)
class demod_20k0f3e_cf(fm_demod_cf):
<|fim_middle|>
class demod_200kf3e_cf(fm_demod_cf):
"""
WFM demodulation block, mono.
This block demodulates a complex, downconverted, wideband FM
channel conforming to 200KF3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
75000, # Deviation
15000, # Audio passband
16000, # Audio stopband
20.0) # Audio gain
<|fim▁end|> | """
NBFM demodulation block, 20 KHz channels
This block demodulates a complex, downconverted, narrowband FM
channel conforming to 20K0F3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
5000, # Deviation
3000, # Audio passband frequency
4500) # Audio stopband frequency |
<|file_name|>fm_demod.py<|end_file_name|><|fim▁begin|>#
# Copyright 2006,2007 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr, optfir
from gnuradio.blks2impl.fm_emph import fm_deemph
from math import pi
class fm_demod_cf(gr.hier_block2):
"""
Generalized FM demodulation block with deemphasis and audio
filtering.
This block demodulates a band-limited, complex down-converted FM
channel into the the original baseband signal, optionally applying
deemphasis. Low pass filtering is done on the resultant signal. It
produces an output float strem in the range of [-1.0, +1.0].
@param channel_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param deviation: maximum FM deviation (default = 5000)
@type deviation: float
@param audio_decim: input to output decimation rate
@type audio_decim: integer
@param audio_pass: audio low pass filter passband frequency
@type audio_pass: float
@param audio_stop: audio low pass filter stop frequency
@type audio_stop: float
@param gain: gain applied to audio output (default = 1.0)
@type gain: float
@param tau: deemphasis time constant (default = 75e-6), specify 'None'
to prevent deemphasis
"""
def __init__(self, channel_rate, audio_decim, deviation,
audio_pass, audio_stop, gain=1.0, tau=75e-6):
gr.hier_block2.__init__(self, "fm_demod_cf",
gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
gr.io_signature(1, 1, gr.sizeof_float)) # Output signature
k = channel_rate/(2*pi*deviation)
QUAD = gr.quadrature_demod_cf(k)
audio_taps = optfir.low_pass(gain, # Filter gain
channel_rate, # Sample rate
audio_pass, # Audio passband
audio_stop, # Audio stopband
0.1, # Passband ripple
60) # Stopband attenuation
LPF = gr.fir_filter_fff(audio_decim, audio_taps)
if tau is not None:
DEEMPH = fm_deemph(channel_rate, tau)
self.connect(self, QUAD, DEEMPH, LPF, self)
else:
self.connect(self, QUAD, LPF, self)
class demod_20k0f3e_cf(fm_demod_cf):
"""
NBFM demodulation block, 20 KHz channels
This block demodulates a complex, downconverted, narrowband FM
channel conforming to 20K0F3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
<|fim_middle|>
class demod_200kf3e_cf(fm_demod_cf):
"""
WFM demodulation block, mono.
This block demodulates a complex, downconverted, wideband FM
channel conforming to 200KF3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
75000, # Deviation
15000, # Audio passband
16000, # Audio stopband
20.0) # Audio gain
<|fim▁end|> | fm_demod_cf.__init__(self, channel_rate, audio_decim,
5000, # Deviation
3000, # Audio passband frequency
4500) # Audio stopband frequency |
<|file_name|>fm_demod.py<|end_file_name|><|fim▁begin|>#
# Copyright 2006,2007 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr, optfir
from gnuradio.blks2impl.fm_emph import fm_deemph
from math import pi
class fm_demod_cf(gr.hier_block2):
"""
Generalized FM demodulation block with deemphasis and audio
filtering.
This block demodulates a band-limited, complex down-converted FM
channel into the the original baseband signal, optionally applying
deemphasis. Low pass filtering is done on the resultant signal. It
produces an output float strem in the range of [-1.0, +1.0].
@param channel_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param deviation: maximum FM deviation (default = 5000)
@type deviation: float
@param audio_decim: input to output decimation rate
@type audio_decim: integer
@param audio_pass: audio low pass filter passband frequency
@type audio_pass: float
@param audio_stop: audio low pass filter stop frequency
@type audio_stop: float
@param gain: gain applied to audio output (default = 1.0)
@type gain: float
@param tau: deemphasis time constant (default = 75e-6), specify 'None'
to prevent deemphasis
"""
def __init__(self, channel_rate, audio_decim, deviation,
audio_pass, audio_stop, gain=1.0, tau=75e-6):
gr.hier_block2.__init__(self, "fm_demod_cf",
gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
gr.io_signature(1, 1, gr.sizeof_float)) # Output signature
k = channel_rate/(2*pi*deviation)
QUAD = gr.quadrature_demod_cf(k)
audio_taps = optfir.low_pass(gain, # Filter gain
channel_rate, # Sample rate
audio_pass, # Audio passband
audio_stop, # Audio stopband
0.1, # Passband ripple
60) # Stopband attenuation
LPF = gr.fir_filter_fff(audio_decim, audio_taps)
if tau is not None:
DEEMPH = fm_deemph(channel_rate, tau)
self.connect(self, QUAD, DEEMPH, LPF, self)
else:
self.connect(self, QUAD, LPF, self)
class demod_20k0f3e_cf(fm_demod_cf):
"""
NBFM demodulation block, 20 KHz channels
This block demodulates a complex, downconverted, narrowband FM
channel conforming to 20K0F3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
5000, # Deviation
3000, # Audio passband frequency
4500) # Audio stopband frequency
class demod_200kf3e_cf(fm_demod_cf):
<|fim_middle|>
<|fim▁end|> | """
WFM demodulation block, mono.
This block demodulates a complex, downconverted, wideband FM
channel conforming to 200KF3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
75000, # Deviation
15000, # Audio passband
16000, # Audio stopband
20.0) # Audio gain |
<|file_name|>fm_demod.py<|end_file_name|><|fim▁begin|>#
# Copyright 2006,2007 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr, optfir
from gnuradio.blks2impl.fm_emph import fm_deemph
from math import pi
class fm_demod_cf(gr.hier_block2):
"""
Generalized FM demodulation block with deemphasis and audio
filtering.
This block demodulates a band-limited, complex down-converted FM
channel into the the original baseband signal, optionally applying
deemphasis. Low pass filtering is done on the resultant signal. It
produces an output float strem in the range of [-1.0, +1.0].
@param channel_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param deviation: maximum FM deviation (default = 5000)
@type deviation: float
@param audio_decim: input to output decimation rate
@type audio_decim: integer
@param audio_pass: audio low pass filter passband frequency
@type audio_pass: float
@param audio_stop: audio low pass filter stop frequency
@type audio_stop: float
@param gain: gain applied to audio output (default = 1.0)
@type gain: float
@param tau: deemphasis time constant (default = 75e-6), specify 'None'
to prevent deemphasis
"""
def __init__(self, channel_rate, audio_decim, deviation,
audio_pass, audio_stop, gain=1.0, tau=75e-6):
gr.hier_block2.__init__(self, "fm_demod_cf",
gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
gr.io_signature(1, 1, gr.sizeof_float)) # Output signature
k = channel_rate/(2*pi*deviation)
QUAD = gr.quadrature_demod_cf(k)
audio_taps = optfir.low_pass(gain, # Filter gain
channel_rate, # Sample rate
audio_pass, # Audio passband
audio_stop, # Audio stopband
0.1, # Passband ripple
60) # Stopband attenuation
LPF = gr.fir_filter_fff(audio_decim, audio_taps)
if tau is not None:
DEEMPH = fm_deemph(channel_rate, tau)
self.connect(self, QUAD, DEEMPH, LPF, self)
else:
self.connect(self, QUAD, LPF, self)
class demod_20k0f3e_cf(fm_demod_cf):
"""
NBFM demodulation block, 20 KHz channels
This block demodulates a complex, downconverted, narrowband FM
channel conforming to 20K0F3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
5000, # Deviation
3000, # Audio passband frequency
4500) # Audio stopband frequency
class demod_200kf3e_cf(fm_demod_cf):
"""
WFM demodulation block, mono.
This block demodulates a complex, downconverted, wideband FM
channel conforming to 200KF3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
<|fim_middle|>
<|fim▁end|> | fm_demod_cf.__init__(self, channel_rate, audio_decim,
75000, # Deviation
15000, # Audio passband
16000, # Audio stopband
20.0) # Audio gain |
<|file_name|>fm_demod.py<|end_file_name|><|fim▁begin|>#
# Copyright 2006,2007 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr, optfir
from gnuradio.blks2impl.fm_emph import fm_deemph
from math import pi
class fm_demod_cf(gr.hier_block2):
"""
Generalized FM demodulation block with deemphasis and audio
filtering.
This block demodulates a band-limited, complex down-converted FM
channel into the the original baseband signal, optionally applying
deemphasis. Low pass filtering is done on the resultant signal. It
produces an output float strem in the range of [-1.0, +1.0].
@param channel_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param deviation: maximum FM deviation (default = 5000)
@type deviation: float
@param audio_decim: input to output decimation rate
@type audio_decim: integer
@param audio_pass: audio low pass filter passband frequency
@type audio_pass: float
@param audio_stop: audio low pass filter stop frequency
@type audio_stop: float
@param gain: gain applied to audio output (default = 1.0)
@type gain: float
@param tau: deemphasis time constant (default = 75e-6), specify 'None'
to prevent deemphasis
"""
def __init__(self, channel_rate, audio_decim, deviation,
audio_pass, audio_stop, gain=1.0, tau=75e-6):
gr.hier_block2.__init__(self, "fm_demod_cf",
gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
gr.io_signature(1, 1, gr.sizeof_float)) # Output signature
k = channel_rate/(2*pi*deviation)
QUAD = gr.quadrature_demod_cf(k)
audio_taps = optfir.low_pass(gain, # Filter gain
channel_rate, # Sample rate
audio_pass, # Audio passband
audio_stop, # Audio stopband
0.1, # Passband ripple
60) # Stopband attenuation
LPF = gr.fir_filter_fff(audio_decim, audio_taps)
if tau is not None:
<|fim_middle|>
else:
self.connect(self, QUAD, LPF, self)
class demod_20k0f3e_cf(fm_demod_cf):
"""
NBFM demodulation block, 20 KHz channels
This block demodulates a complex, downconverted, narrowband FM
channel conforming to 20K0F3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
5000, # Deviation
3000, # Audio passband frequency
4500) # Audio stopband frequency
class demod_200kf3e_cf(fm_demod_cf):
"""
WFM demodulation block, mono.
This block demodulates a complex, downconverted, wideband FM
channel conforming to 200KF3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
75000, # Deviation
15000, # Audio passband
16000, # Audio stopband
20.0) # Audio gain
<|fim▁end|> | DEEMPH = fm_deemph(channel_rate, tau)
self.connect(self, QUAD, DEEMPH, LPF, self) |
<|file_name|>fm_demod.py<|end_file_name|><|fim▁begin|>#
# Copyright 2006,2007 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr, optfir
from gnuradio.blks2impl.fm_emph import fm_deemph
from math import pi
class fm_demod_cf(gr.hier_block2):
"""
Generalized FM demodulation block with deemphasis and audio
filtering.
This block demodulates a band-limited, complex down-converted FM
channel into the the original baseband signal, optionally applying
deemphasis. Low pass filtering is done on the resultant signal. It
produces an output float strem in the range of [-1.0, +1.0].
@param channel_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param deviation: maximum FM deviation (default = 5000)
@type deviation: float
@param audio_decim: input to output decimation rate
@type audio_decim: integer
@param audio_pass: audio low pass filter passband frequency
@type audio_pass: float
@param audio_stop: audio low pass filter stop frequency
@type audio_stop: float
@param gain: gain applied to audio output (default = 1.0)
@type gain: float
@param tau: deemphasis time constant (default = 75e-6), specify 'None'
to prevent deemphasis
"""
def __init__(self, channel_rate, audio_decim, deviation,
audio_pass, audio_stop, gain=1.0, tau=75e-6):
gr.hier_block2.__init__(self, "fm_demod_cf",
gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
gr.io_signature(1, 1, gr.sizeof_float)) # Output signature
k = channel_rate/(2*pi*deviation)
QUAD = gr.quadrature_demod_cf(k)
audio_taps = optfir.low_pass(gain, # Filter gain
channel_rate, # Sample rate
audio_pass, # Audio passband
audio_stop, # Audio stopband
0.1, # Passband ripple
60) # Stopband attenuation
LPF = gr.fir_filter_fff(audio_decim, audio_taps)
if tau is not None:
DEEMPH = fm_deemph(channel_rate, tau)
self.connect(self, QUAD, DEEMPH, LPF, self)
else:
<|fim_middle|>
class demod_20k0f3e_cf(fm_demod_cf):
"""
NBFM demodulation block, 20 KHz channels
This block demodulates a complex, downconverted, narrowband FM
channel conforming to 20K0F3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
5000, # Deviation
3000, # Audio passband frequency
4500) # Audio stopband frequency
class demod_200kf3e_cf(fm_demod_cf):
"""
WFM demodulation block, mono.
This block demodulates a complex, downconverted, wideband FM
channel conforming to 200KF3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
75000, # Deviation
15000, # Audio passband
16000, # Audio stopband
20.0) # Audio gain
<|fim▁end|> | self.connect(self, QUAD, LPF, self) |
<|file_name|>fm_demod.py<|end_file_name|><|fim▁begin|>#
# Copyright 2006,2007 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr, optfir
from gnuradio.blks2impl.fm_emph import fm_deemph
from math import pi
class fm_demod_cf(gr.hier_block2):
"""
Generalized FM demodulation block with deemphasis and audio
filtering.
This block demodulates a band-limited, complex down-converted FM
channel into the the original baseband signal, optionally applying
deemphasis. Low pass filtering is done on the resultant signal. It
produces an output float strem in the range of [-1.0, +1.0].
@param channel_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param deviation: maximum FM deviation (default = 5000)
@type deviation: float
@param audio_decim: input to output decimation rate
@type audio_decim: integer
@param audio_pass: audio low pass filter passband frequency
@type audio_pass: float
@param audio_stop: audio low pass filter stop frequency
@type audio_stop: float
@param gain: gain applied to audio output (default = 1.0)
@type gain: float
@param tau: deemphasis time constant (default = 75e-6), specify 'None'
to prevent deemphasis
"""
def <|fim_middle|>(self, channel_rate, audio_decim, deviation,
audio_pass, audio_stop, gain=1.0, tau=75e-6):
gr.hier_block2.__init__(self, "fm_demod_cf",
gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
gr.io_signature(1, 1, gr.sizeof_float)) # Output signature
k = channel_rate/(2*pi*deviation)
QUAD = gr.quadrature_demod_cf(k)
audio_taps = optfir.low_pass(gain, # Filter gain
channel_rate, # Sample rate
audio_pass, # Audio passband
audio_stop, # Audio stopband
0.1, # Passband ripple
60) # Stopband attenuation
LPF = gr.fir_filter_fff(audio_decim, audio_taps)
if tau is not None:
DEEMPH = fm_deemph(channel_rate, tau)
self.connect(self, QUAD, DEEMPH, LPF, self)
else:
self.connect(self, QUAD, LPF, self)
class demod_20k0f3e_cf(fm_demod_cf):
"""
NBFM demodulation block, 20 KHz channels
This block demodulates a complex, downconverted, narrowband FM
channel conforming to 20K0F3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
5000, # Deviation
3000, # Audio passband frequency
4500) # Audio stopband frequency
class demod_200kf3e_cf(fm_demod_cf):
"""
WFM demodulation block, mono.
This block demodulates a complex, downconverted, wideband FM
channel conforming to 200KF3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
75000, # Deviation
15000, # Audio passband
16000, # Audio stopband
20.0) # Audio gain
<|fim▁end|> | __init__ |
<|file_name|>fm_demod.py<|end_file_name|><|fim▁begin|>#
# Copyright 2006,2007 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr, optfir
from gnuradio.blks2impl.fm_emph import fm_deemph
from math import pi
class fm_demod_cf(gr.hier_block2):
"""
Generalized FM demodulation block with deemphasis and audio
filtering.
This block demodulates a band-limited, complex down-converted FM
channel into the the original baseband signal, optionally applying
deemphasis. Low pass filtering is done on the resultant signal. It
produces an output float strem in the range of [-1.0, +1.0].
@param channel_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param deviation: maximum FM deviation (default = 5000)
@type deviation: float
@param audio_decim: input to output decimation rate
@type audio_decim: integer
@param audio_pass: audio low pass filter passband frequency
@type audio_pass: float
@param audio_stop: audio low pass filter stop frequency
@type audio_stop: float
@param gain: gain applied to audio output (default = 1.0)
@type gain: float
@param tau: deemphasis time constant (default = 75e-6), specify 'None'
to prevent deemphasis
"""
def __init__(self, channel_rate, audio_decim, deviation,
audio_pass, audio_stop, gain=1.0, tau=75e-6):
gr.hier_block2.__init__(self, "fm_demod_cf",
gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
gr.io_signature(1, 1, gr.sizeof_float)) # Output signature
k = channel_rate/(2*pi*deviation)
QUAD = gr.quadrature_demod_cf(k)
audio_taps = optfir.low_pass(gain, # Filter gain
channel_rate, # Sample rate
audio_pass, # Audio passband
audio_stop, # Audio stopband
0.1, # Passband ripple
60) # Stopband attenuation
LPF = gr.fir_filter_fff(audio_decim, audio_taps)
if tau is not None:
DEEMPH = fm_deemph(channel_rate, tau)
self.connect(self, QUAD, DEEMPH, LPF, self)
else:
self.connect(self, QUAD, LPF, self)
class demod_20k0f3e_cf(fm_demod_cf):
"""
NBFM demodulation block, 20 KHz channels
This block demodulates a complex, downconverted, narrowband FM
channel conforming to 20K0F3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def <|fim_middle|>(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
5000, # Deviation
3000, # Audio passband frequency
4500) # Audio stopband frequency
class demod_200kf3e_cf(fm_demod_cf):
"""
WFM demodulation block, mono.
This block demodulates a complex, downconverted, wideband FM
channel conforming to 200KF3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
75000, # Deviation
15000, # Audio passband
16000, # Audio stopband
20.0) # Audio gain
<|fim▁end|> | __init__ |
<|file_name|>fm_demod.py<|end_file_name|><|fim▁begin|>#
# Copyright 2006,2007 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr, optfir
from gnuradio.blks2impl.fm_emph import fm_deemph
from math import pi
class fm_demod_cf(gr.hier_block2):
"""
Generalized FM demodulation block with deemphasis and audio
filtering.
This block demodulates a band-limited, complex down-converted FM
channel into the the original baseband signal, optionally applying
deemphasis. Low pass filtering is done on the resultant signal. It
produces an output float strem in the range of [-1.0, +1.0].
@param channel_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param deviation: maximum FM deviation (default = 5000)
@type deviation: float
@param audio_decim: input to output decimation rate
@type audio_decim: integer
@param audio_pass: audio low pass filter passband frequency
@type audio_pass: float
@param audio_stop: audio low pass filter stop frequency
@type audio_stop: float
@param gain: gain applied to audio output (default = 1.0)
@type gain: float
@param tau: deemphasis time constant (default = 75e-6), specify 'None'
to prevent deemphasis
"""
def __init__(self, channel_rate, audio_decim, deviation,
audio_pass, audio_stop, gain=1.0, tau=75e-6):
gr.hier_block2.__init__(self, "fm_demod_cf",
gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
gr.io_signature(1, 1, gr.sizeof_float)) # Output signature
k = channel_rate/(2*pi*deviation)
QUAD = gr.quadrature_demod_cf(k)
audio_taps = optfir.low_pass(gain, # Filter gain
channel_rate, # Sample rate
audio_pass, # Audio passband
audio_stop, # Audio stopband
0.1, # Passband ripple
60) # Stopband attenuation
LPF = gr.fir_filter_fff(audio_decim, audio_taps)
if tau is not None:
DEEMPH = fm_deemph(channel_rate, tau)
self.connect(self, QUAD, DEEMPH, LPF, self)
else:
self.connect(self, QUAD, LPF, self)
class demod_20k0f3e_cf(fm_demod_cf):
"""
NBFM demodulation block, 20 KHz channels
This block demodulates a complex, downconverted, narrowband FM
channel conforming to 20K0F3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def __init__(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
5000, # Deviation
3000, # Audio passband frequency
4500) # Audio stopband frequency
class demod_200kf3e_cf(fm_demod_cf):
"""
WFM demodulation block, mono.
This block demodulates a complex, downconverted, wideband FM
channel conforming to 200KF3E emission standards, outputting
floats in the range [-1.0, +1.0].
@param sample_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param audio_decim: input to output decimation rate
@type audio_decim: integer
"""
def <|fim_middle|>(self, channel_rate, audio_decim):
fm_demod_cf.__init__(self, channel_rate, audio_decim,
75000, # Deviation
15000, # Audio passband
16000, # Audio stopband
20.0) # Audio gain
<|fim▁end|> | __init__ |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from click_plugins import with_plugins
from pkg_resources import iter_entry_points
import click
<|fim▁hole|> context_settings=dict(help_option_names=['-h', '--help']))
@click.version_option(message='%(version)s')
def main():
pass<|fim▁end|> |
@with_plugins(iter_entry_points('girder.cli_plugins'))
@click.group(help='Girder: data management platform for the web.', |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from click_plugins import with_plugins
from pkg_resources import iter_entry_points
import click
@with_plugins(iter_entry_points('girder.cli_plugins'))
@click.group(help='Girder: data management platform for the web.',
context_settings=dict(help_option_names=['-h', '--help']))
@click.version_option(message='%(version)s')
def main():
<|fim_middle|>
<|fim▁end|> | pass |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from click_plugins import with_plugins
from pkg_resources import iter_entry_points
import click
@with_plugins(iter_entry_points('girder.cli_plugins'))
@click.group(help='Girder: data management platform for the web.',
context_settings=dict(help_option_names=['-h', '--help']))
@click.version_option(message='%(version)s')
def <|fim_middle|>():
pass
<|fim▁end|> | main |
<|file_name|>testkmeans.py<|end_file_name|><|fim▁begin|>"""Run tests for the kmeans portion of the kmeans module"""
import kmeans.kmeans.kmeans as kmeans
import numpy as np
import random
def test_1dim_distance():
"""See if this contraption works in 1 dimension"""
num1 = random.random()
num2 = random.random()
assert kmeans.ndim_euclidean_distance(num1, num2) == abs(num1-num2)
def test_ndim_distance():
"""Test to see if changing val by 1 does what it ought to do
convert to float to integer because floating arithmetic makes testing
analytic functions a mess"""
rand = random.random
point1 = [rand(), rand(), rand(), rand(), rand(), rand()]
point2 = [point1[0]+1] + point1[1:] # just shift x to the right by 1
assert int(round(kmeans.ndim_euclidean_distance(point1, point2))) == 1
def test_maxiters():
"""ensure the iteration ceiling works"""
# assert kmeans.should_iter([], [], iterations=29) == True
assert kmeans.should_iter([], [], iterations=30) == False
assert kmeans.should_iter([], [], iterations=31) == False<|fim▁hole|> dimensions = random.randrange(1, 100)
k = random.randrange(1, 100)
centroids = kmeans.random_centroids(k, dimensions)
for centroid in centroids:
assert len(centroid) == dimensions
def test_iterated_centroid():
"""ensure that the average across each dimension is returned"""
new_centroid = kmeans.iterated_centroid([[1, 1, 1], [2, 2, 2]],\
[[100, 200, 300]], [(0, 0), (1, 0)])
np.testing.assert_allclose(new_centroid, np.array([[1.5, 1.5, 1.5]]),\
rtol=1e-5)<|fim▁end|> |
def test_random_centroid_dimensions():
"""ensure the correct number of dimensions""" |
<|file_name|>testkmeans.py<|end_file_name|><|fim▁begin|>"""Run tests for the kmeans portion of the kmeans module"""
import kmeans.kmeans.kmeans as kmeans
import numpy as np
import random
def test_1dim_distance():
<|fim_middle|>
def test_ndim_distance():
"""Test to see if changing val by 1 does what it ought to do
convert to float to integer because floating arithmetic makes testing
analytic functions a mess"""
rand = random.random
point1 = [rand(), rand(), rand(), rand(), rand(), rand()]
point2 = [point1[0]+1] + point1[1:] # just shift x to the right by 1
assert int(round(kmeans.ndim_euclidean_distance(point1, point2))) == 1
def test_maxiters():
"""ensure the iteration ceiling works"""
# assert kmeans.should_iter([], [], iterations=29) == True
assert kmeans.should_iter([], [], iterations=30) == False
assert kmeans.should_iter([], [], iterations=31) == False
def test_random_centroid_dimensions():
"""ensure the correct number of dimensions"""
dimensions = random.randrange(1, 100)
k = random.randrange(1, 100)
centroids = kmeans.random_centroids(k, dimensions)
for centroid in centroids:
assert len(centroid) == dimensions
def test_iterated_centroid():
"""ensure that the average across each dimension is returned"""
new_centroid = kmeans.iterated_centroid([[1, 1, 1], [2, 2, 2]],\
[[100, 200, 300]], [(0, 0), (1, 0)])
np.testing.assert_allclose(new_centroid, np.array([[1.5, 1.5, 1.5]]),\
rtol=1e-5)
<|fim▁end|> | """See if this contraption works in 1 dimension"""
num1 = random.random()
num2 = random.random()
assert kmeans.ndim_euclidean_distance(num1, num2) == abs(num1-num2) |
<|file_name|>testkmeans.py<|end_file_name|><|fim▁begin|>"""Run tests for the kmeans portion of the kmeans module"""
import kmeans.kmeans.kmeans as kmeans
import numpy as np
import random
def test_1dim_distance():
"""See if this contraption works in 1 dimension"""
num1 = random.random()
num2 = random.random()
assert kmeans.ndim_euclidean_distance(num1, num2) == abs(num1-num2)
def test_ndim_distance():
<|fim_middle|>
def test_maxiters():
"""ensure the iteration ceiling works"""
# assert kmeans.should_iter([], [], iterations=29) == True
assert kmeans.should_iter([], [], iterations=30) == False
assert kmeans.should_iter([], [], iterations=31) == False
def test_random_centroid_dimensions():
"""ensure the correct number of dimensions"""
dimensions = random.randrange(1, 100)
k = random.randrange(1, 100)
centroids = kmeans.random_centroids(k, dimensions)
for centroid in centroids:
assert len(centroid) == dimensions
def test_iterated_centroid():
"""ensure that the average across each dimension is returned"""
new_centroid = kmeans.iterated_centroid([[1, 1, 1], [2, 2, 2]],\
[[100, 200, 300]], [(0, 0), (1, 0)])
np.testing.assert_allclose(new_centroid, np.array([[1.5, 1.5, 1.5]]),\
rtol=1e-5)
<|fim▁end|> | """Test to see if changing val by 1 does what it ought to do
convert to float to integer because floating arithmetic makes testing
analytic functions a mess"""
rand = random.random
point1 = [rand(), rand(), rand(), rand(), rand(), rand()]
point2 = [point1[0]+1] + point1[1:] # just shift x to the right by 1
assert int(round(kmeans.ndim_euclidean_distance(point1, point2))) == 1 |
<|file_name|>testkmeans.py<|end_file_name|><|fim▁begin|>"""Run tests for the kmeans portion of the kmeans module"""
import kmeans.kmeans.kmeans as kmeans
import numpy as np
import random
def test_1dim_distance():
"""See if this contraption works in 1 dimension"""
num1 = random.random()
num2 = random.random()
assert kmeans.ndim_euclidean_distance(num1, num2) == abs(num1-num2)
def test_ndim_distance():
"""Test to see if changing val by 1 does what it ought to do
convert to float to integer because floating arithmetic makes testing
analytic functions a mess"""
rand = random.random
point1 = [rand(), rand(), rand(), rand(), rand(), rand()]
point2 = [point1[0]+1] + point1[1:] # just shift x to the right by 1
assert int(round(kmeans.ndim_euclidean_distance(point1, point2))) == 1
def test_maxiters():
<|fim_middle|>
def test_random_centroid_dimensions():
"""ensure the correct number of dimensions"""
dimensions = random.randrange(1, 100)
k = random.randrange(1, 100)
centroids = kmeans.random_centroids(k, dimensions)
for centroid in centroids:
assert len(centroid) == dimensions
def test_iterated_centroid():
"""ensure that the average across each dimension is returned"""
new_centroid = kmeans.iterated_centroid([[1, 1, 1], [2, 2, 2]],\
[[100, 200, 300]], [(0, 0), (1, 0)])
np.testing.assert_allclose(new_centroid, np.array([[1.5, 1.5, 1.5]]),\
rtol=1e-5)
<|fim▁end|> | """ensure the iteration ceiling works"""
# assert kmeans.should_iter([], [], iterations=29) == True
assert kmeans.should_iter([], [], iterations=30) == False
assert kmeans.should_iter([], [], iterations=31) == False |
<|file_name|>testkmeans.py<|end_file_name|><|fim▁begin|>"""Run tests for the kmeans portion of the kmeans module"""
import kmeans.kmeans.kmeans as kmeans
import numpy as np
import random
def test_1dim_distance():
"""See if this contraption works in 1 dimension"""
num1 = random.random()
num2 = random.random()
assert kmeans.ndim_euclidean_distance(num1, num2) == abs(num1-num2)
def test_ndim_distance():
"""Test to see if changing val by 1 does what it ought to do
convert to float to integer because floating arithmetic makes testing
analytic functions a mess"""
rand = random.random
point1 = [rand(), rand(), rand(), rand(), rand(), rand()]
point2 = [point1[0]+1] + point1[1:] # just shift x to the right by 1
assert int(round(kmeans.ndim_euclidean_distance(point1, point2))) == 1
def test_maxiters():
"""ensure the iteration ceiling works"""
# assert kmeans.should_iter([], [], iterations=29) == True
assert kmeans.should_iter([], [], iterations=30) == False
assert kmeans.should_iter([], [], iterations=31) == False
def test_random_centroid_dimensions():
<|fim_middle|>
def test_iterated_centroid():
"""ensure that the average across each dimension is returned"""
new_centroid = kmeans.iterated_centroid([[1, 1, 1], [2, 2, 2]],\
[[100, 200, 300]], [(0, 0), (1, 0)])
np.testing.assert_allclose(new_centroid, np.array([[1.5, 1.5, 1.5]]),\
rtol=1e-5)
<|fim▁end|> | """ensure the correct number of dimensions"""
dimensions = random.randrange(1, 100)
k = random.randrange(1, 100)
centroids = kmeans.random_centroids(k, dimensions)
for centroid in centroids:
assert len(centroid) == dimensions |
<|file_name|>testkmeans.py<|end_file_name|><|fim▁begin|>"""Run tests for the kmeans portion of the kmeans module"""
import kmeans.kmeans.kmeans as kmeans
import numpy as np
import random
def test_1dim_distance():
"""See if this contraption works in 1 dimension"""
num1 = random.random()
num2 = random.random()
assert kmeans.ndim_euclidean_distance(num1, num2) == abs(num1-num2)
def test_ndim_distance():
"""Test to see if changing val by 1 does what it ought to do
convert to float to integer because floating arithmetic makes testing
analytic functions a mess"""
rand = random.random
point1 = [rand(), rand(), rand(), rand(), rand(), rand()]
point2 = [point1[0]+1] + point1[1:] # just shift x to the right by 1
assert int(round(kmeans.ndim_euclidean_distance(point1, point2))) == 1
def test_maxiters():
"""ensure the iteration ceiling works"""
# assert kmeans.should_iter([], [], iterations=29) == True
assert kmeans.should_iter([], [], iterations=30) == False
assert kmeans.should_iter([], [], iterations=31) == False
def test_random_centroid_dimensions():
"""ensure the correct number of dimensions"""
dimensions = random.randrange(1, 100)
k = random.randrange(1, 100)
centroids = kmeans.random_centroids(k, dimensions)
for centroid in centroids:
assert len(centroid) == dimensions
def test_iterated_centroid():
<|fim_middle|>
<|fim▁end|> | """ensure that the average across each dimension is returned"""
new_centroid = kmeans.iterated_centroid([[1, 1, 1], [2, 2, 2]],\
[[100, 200, 300]], [(0, 0), (1, 0)])
np.testing.assert_allclose(new_centroid, np.array([[1.5, 1.5, 1.5]]),\
rtol=1e-5) |
<|file_name|>testkmeans.py<|end_file_name|><|fim▁begin|>"""Run tests for the kmeans portion of the kmeans module"""
import kmeans.kmeans.kmeans as kmeans
import numpy as np
import random
def <|fim_middle|>():
"""See if this contraption works in 1 dimension"""
num1 = random.random()
num2 = random.random()
assert kmeans.ndim_euclidean_distance(num1, num2) == abs(num1-num2)
def test_ndim_distance():
"""Test to see if changing val by 1 does what it ought to do
convert to float to integer because floating arithmetic makes testing
analytic functions a mess"""
rand = random.random
point1 = [rand(), rand(), rand(), rand(), rand(), rand()]
point2 = [point1[0]+1] + point1[1:] # just shift x to the right by 1
assert int(round(kmeans.ndim_euclidean_distance(point1, point2))) == 1
def test_maxiters():
"""ensure the iteration ceiling works"""
# assert kmeans.should_iter([], [], iterations=29) == True
assert kmeans.should_iter([], [], iterations=30) == False
assert kmeans.should_iter([], [], iterations=31) == False
def test_random_centroid_dimensions():
"""ensure the correct number of dimensions"""
dimensions = random.randrange(1, 100)
k = random.randrange(1, 100)
centroids = kmeans.random_centroids(k, dimensions)
for centroid in centroids:
assert len(centroid) == dimensions
def test_iterated_centroid():
"""ensure that the average across each dimension is returned"""
new_centroid = kmeans.iterated_centroid([[1, 1, 1], [2, 2, 2]],\
[[100, 200, 300]], [(0, 0), (1, 0)])
np.testing.assert_allclose(new_centroid, np.array([[1.5, 1.5, 1.5]]),\
rtol=1e-5)
<|fim▁end|> | test_1dim_distance |
<|file_name|>testkmeans.py<|end_file_name|><|fim▁begin|>"""Run tests for the kmeans portion of the kmeans module"""
import kmeans.kmeans.kmeans as kmeans
import numpy as np
import random
def test_1dim_distance():
"""See if this contraption works in 1 dimension"""
num1 = random.random()
num2 = random.random()
assert kmeans.ndim_euclidean_distance(num1, num2) == abs(num1-num2)
def <|fim_middle|>():
"""Test to see if changing val by 1 does what it ought to do
convert to float to integer because floating arithmetic makes testing
analytic functions a mess"""
rand = random.random
point1 = [rand(), rand(), rand(), rand(), rand(), rand()]
point2 = [point1[0]+1] + point1[1:] # just shift x to the right by 1
assert int(round(kmeans.ndim_euclidean_distance(point1, point2))) == 1
def test_maxiters():
"""ensure the iteration ceiling works"""
# assert kmeans.should_iter([], [], iterations=29) == True
assert kmeans.should_iter([], [], iterations=30) == False
assert kmeans.should_iter([], [], iterations=31) == False
def test_random_centroid_dimensions():
"""ensure the correct number of dimensions"""
dimensions = random.randrange(1, 100)
k = random.randrange(1, 100)
centroids = kmeans.random_centroids(k, dimensions)
for centroid in centroids:
assert len(centroid) == dimensions
def test_iterated_centroid():
"""ensure that the average across each dimension is returned"""
new_centroid = kmeans.iterated_centroid([[1, 1, 1], [2, 2, 2]],\
[[100, 200, 300]], [(0, 0), (1, 0)])
np.testing.assert_allclose(new_centroid, np.array([[1.5, 1.5, 1.5]]),\
rtol=1e-5)
<|fim▁end|> | test_ndim_distance |
<|file_name|>testkmeans.py<|end_file_name|><|fim▁begin|>"""Run tests for the kmeans portion of the kmeans module"""
import kmeans.kmeans.kmeans as kmeans
import numpy as np
import random
def test_1dim_distance():
"""See if this contraption works in 1 dimension"""
num1 = random.random()
num2 = random.random()
assert kmeans.ndim_euclidean_distance(num1, num2) == abs(num1-num2)
def test_ndim_distance():
"""Test to see if changing val by 1 does what it ought to do
convert to float to integer because floating arithmetic makes testing
analytic functions a mess"""
rand = random.random
point1 = [rand(), rand(), rand(), rand(), rand(), rand()]
point2 = [point1[0]+1] + point1[1:] # just shift x to the right by 1
assert int(round(kmeans.ndim_euclidean_distance(point1, point2))) == 1
def <|fim_middle|>():
"""ensure the iteration ceiling works"""
# assert kmeans.should_iter([], [], iterations=29) == True
assert kmeans.should_iter([], [], iterations=30) == False
assert kmeans.should_iter([], [], iterations=31) == False
def test_random_centroid_dimensions():
"""ensure the correct number of dimensions"""
dimensions = random.randrange(1, 100)
k = random.randrange(1, 100)
centroids = kmeans.random_centroids(k, dimensions)
for centroid in centroids:
assert len(centroid) == dimensions
def test_iterated_centroid():
"""ensure that the average across each dimension is returned"""
new_centroid = kmeans.iterated_centroid([[1, 1, 1], [2, 2, 2]],\
[[100, 200, 300]], [(0, 0), (1, 0)])
np.testing.assert_allclose(new_centroid, np.array([[1.5, 1.5, 1.5]]),\
rtol=1e-5)
<|fim▁end|> | test_maxiters |
<|file_name|>testkmeans.py<|end_file_name|><|fim▁begin|>"""Run tests for the kmeans portion of the kmeans module"""
import kmeans.kmeans.kmeans as kmeans
import numpy as np
import random
def test_1dim_distance():
"""See if this contraption works in 1 dimension"""
num1 = random.random()
num2 = random.random()
assert kmeans.ndim_euclidean_distance(num1, num2) == abs(num1-num2)
def test_ndim_distance():
"""Test to see if changing val by 1 does what it ought to do
convert to float to integer because floating arithmetic makes testing
analytic functions a mess"""
rand = random.random
point1 = [rand(), rand(), rand(), rand(), rand(), rand()]
point2 = [point1[0]+1] + point1[1:] # just shift x to the right by 1
assert int(round(kmeans.ndim_euclidean_distance(point1, point2))) == 1
def test_maxiters():
"""ensure the iteration ceiling works"""
# assert kmeans.should_iter([], [], iterations=29) == True
assert kmeans.should_iter([], [], iterations=30) == False
assert kmeans.should_iter([], [], iterations=31) == False
def <|fim_middle|>():
"""ensure the correct number of dimensions"""
dimensions = random.randrange(1, 100)
k = random.randrange(1, 100)
centroids = kmeans.random_centroids(k, dimensions)
for centroid in centroids:
assert len(centroid) == dimensions
def test_iterated_centroid():
"""ensure that the average across each dimension is returned"""
new_centroid = kmeans.iterated_centroid([[1, 1, 1], [2, 2, 2]],\
[[100, 200, 300]], [(0, 0), (1, 0)])
np.testing.assert_allclose(new_centroid, np.array([[1.5, 1.5, 1.5]]),\
rtol=1e-5)
<|fim▁end|> | test_random_centroid_dimensions |
<|file_name|>testkmeans.py<|end_file_name|><|fim▁begin|>"""Run tests for the kmeans portion of the kmeans module"""
import kmeans.kmeans.kmeans as kmeans
import numpy as np
import random
def test_1dim_distance():
"""See if this contraption works in 1 dimension"""
num1 = random.random()
num2 = random.random()
assert kmeans.ndim_euclidean_distance(num1, num2) == abs(num1-num2)
def test_ndim_distance():
"""Test to see if changing val by 1 does what it ought to do
convert to float to integer because floating arithmetic makes testing
analytic functions a mess"""
rand = random.random
point1 = [rand(), rand(), rand(), rand(), rand(), rand()]
point2 = [point1[0]+1] + point1[1:] # just shift x to the right by 1
assert int(round(kmeans.ndim_euclidean_distance(point1, point2))) == 1
def test_maxiters():
"""ensure the iteration ceiling works"""
# assert kmeans.should_iter([], [], iterations=29) == True
assert kmeans.should_iter([], [], iterations=30) == False
assert kmeans.should_iter([], [], iterations=31) == False
def test_random_centroid_dimensions():
"""ensure the correct number of dimensions"""
dimensions = random.randrange(1, 100)
k = random.randrange(1, 100)
centroids = kmeans.random_centroids(k, dimensions)
for centroid in centroids:
assert len(centroid) == dimensions
def <|fim_middle|>():
"""ensure that the average across each dimension is returned"""
new_centroid = kmeans.iterated_centroid([[1, 1, 1], [2, 2, 2]],\
[[100, 200, 300]], [(0, 0), (1, 0)])
np.testing.assert_allclose(new_centroid, np.array([[1.5, 1.5, 1.5]]),\
rtol=1e-5)
<|fim▁end|> | test_iterated_centroid |
<|file_name|>src.py<|end_file_name|><|fim▁begin|>from itertools import permutations
import re
def create_formula(combination,numbers):
formula = ""
index = 0
for op in combination:
formula += str(numbers[index]) + op
index += 1
formula += numbers[index]
return formula
'''
Unnecessary Funtion
'''
def evaluate(form):
result = 0
for index in range(len(form)):
if form[index] == "+":
result += int(form[index+1])
index += 1
elif form[index] == "-":
result -= int(form[index+1])
index += 1
elif form[index] == "*":
result *= int(form[index+1])
index += 1
elif form[index] == "/":
result //= int(form[index+1])
index += 1
else:
result += int(form[index])
return result
def countdown(numbers):
rightCombinations = []
finalScore = numbers.pop()
combinations = returnAllCombinations(len(numbers) - 1)
perms = list(permutations(numbers))
for combination in combinations:
for permut in perms:
formula = create_formula(combination,permut)
#form = re.split("([*+-/])",formula)
#if int(evaluate(form)) == int(finalScore):
if int(eval(formula)) == int(finalScore):
rightCombinations.append(formula)
return rightCombinations
def returnAllCombinations(size):
listFinal = []
for x in range(0,size):
if len(listFinal) == 0:
for y in range(0,4):
if y == 0:
listFinal.append("+")
elif y == 1:
listFinal.append("-")
elif y == 2:
listFinal.append("*")
else:
listFinal.append("/")
else:
newList = []
for l in listFinal:
for y in range(0,4):
newLine = list(l)
if y == 0:
newLine.append("+")
elif y == 1:
newLine.append("-")
elif y == 2:
newLine.append("*")
else:
newLine.append("/")
newList.append(newLine)
listFinal = list(newList)
return listFinal
out = open("output.txt",'w')
for line in open("input.txt",'r'):<|fim▁hole|><|fim▁end|> | for formula in countdown(line.split(" ")):
out.write(formula)
out.write("\n")
out.write("\n\n") |
<|file_name|>src.py<|end_file_name|><|fim▁begin|>from itertools import permutations
import re
def create_formula(combination,numbers):
<|fim_middle|>
'''
Unnecessary Funtion
'''
def evaluate(form):
result = 0
for index in range(len(form)):
if form[index] == "+":
result += int(form[index+1])
index += 1
elif form[index] == "-":
result -= int(form[index+1])
index += 1
elif form[index] == "*":
result *= int(form[index+1])
index += 1
elif form[index] == "/":
result //= int(form[index+1])
index += 1
else:
result += int(form[index])
return result
def countdown(numbers):
rightCombinations = []
finalScore = numbers.pop()
combinations = returnAllCombinations(len(numbers) - 1)
perms = list(permutations(numbers))
for combination in combinations:
for permut in perms:
formula = create_formula(combination,permut)
#form = re.split("([*+-/])",formula)
#if int(evaluate(form)) == int(finalScore):
if int(eval(formula)) == int(finalScore):
rightCombinations.append(formula)
return rightCombinations
def returnAllCombinations(size):
listFinal = []
for x in range(0,size):
if len(listFinal) == 0:
for y in range(0,4):
if y == 0:
listFinal.append("+")
elif y == 1:
listFinal.append("-")
elif y == 2:
listFinal.append("*")
else:
listFinal.append("/")
else:
newList = []
for l in listFinal:
for y in range(0,4):
newLine = list(l)
if y == 0:
newLine.append("+")
elif y == 1:
newLine.append("-")
elif y == 2:
newLine.append("*")
else:
newLine.append("/")
newList.append(newLine)
listFinal = list(newList)
return listFinal
out = open("output.txt",'w')
for line in open("input.txt",'r'):
for formula in countdown(line.split(" ")):
out.write(formula)
out.write("\n")
out.write("\n\n")
<|fim▁end|> | formula = ""
index = 0
for op in combination:
formula += str(numbers[index]) + op
index += 1
formula += numbers[index]
return formula |
<|file_name|>src.py<|end_file_name|><|fim▁begin|>from itertools import permutations
import re
def create_formula(combination,numbers):
formula = ""
index = 0
for op in combination:
formula += str(numbers[index]) + op
index += 1
formula += numbers[index]
return formula
'''
Unnecessary Funtion
'''
def evaluate(form):
<|fim_middle|>
def countdown(numbers):
rightCombinations = []
finalScore = numbers.pop()
combinations = returnAllCombinations(len(numbers) - 1)
perms = list(permutations(numbers))
for combination in combinations:
for permut in perms:
formula = create_formula(combination,permut)
#form = re.split("([*+-/])",formula)
#if int(evaluate(form)) == int(finalScore):
if int(eval(formula)) == int(finalScore):
rightCombinations.append(formula)
return rightCombinations
def returnAllCombinations(size):
listFinal = []
for x in range(0,size):
if len(listFinal) == 0:
for y in range(0,4):
if y == 0:
listFinal.append("+")
elif y == 1:
listFinal.append("-")
elif y == 2:
listFinal.append("*")
else:
listFinal.append("/")
else:
newList = []
for l in listFinal:
for y in range(0,4):
newLine = list(l)
if y == 0:
newLine.append("+")
elif y == 1:
newLine.append("-")
elif y == 2:
newLine.append("*")
else:
newLine.append("/")
newList.append(newLine)
listFinal = list(newList)
return listFinal
out = open("output.txt",'w')
for line in open("input.txt",'r'):
for formula in countdown(line.split(" ")):
out.write(formula)
out.write("\n")
out.write("\n\n")
<|fim▁end|> | result = 0
for index in range(len(form)):
if form[index] == "+":
result += int(form[index+1])
index += 1
elif form[index] == "-":
result -= int(form[index+1])
index += 1
elif form[index] == "*":
result *= int(form[index+1])
index += 1
elif form[index] == "/":
result //= int(form[index+1])
index += 1
else:
result += int(form[index])
return result |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.