text stringlengths 0 1.05M | meta dict |
|---|---|
__author__ = 'Bohdan Mushkevych'
import time
from collections import OrderedDict
from datetime import datetime
from flow.flow_constants import STEP_NAME_START, STEP_NAME_FINISH
from flow.core.execution_context import ContextDriven, get_flow_logger, valid_context
from flow.core.step_executor import StepExecutor
from flow.core.flow_graph_node import FlowGraphNode
from flow.db.dao.flow_dao import FlowDao
from flow.db.dao.step_dao import StepDao
from flow.db.model.step import Step
from synergy.system.log_recording_handler import LogRecordingHandler
from flow.db.model.flow import Flow, STATE_EMBRYO, STATE_INVALID, STATE_PROCESSED, STATE_IN_PROGRESS
class GraphError(Exception):
pass
class FlowGraph(ContextDriven):
""" Graph of interconnected Nodes, each representing an execution step """
def __init__(self, flow_name):
super(FlowGraph, self).__init__()
self.flow_name = flow_name
# format: {step_name:String -> node:FlowGraphNode}
self._dict = OrderedDict()
self.flow_dao = None
self.log_recording_handler = None
# list of step names, yielded for processing
self.yielded = list()
def __getitem__(self, key):
return self._dict[key]
def __len__(self):
return len(self._dict)
def __iter__(self):
return self
def __next__(self):
return self.next()
def next(self):
""" heart of the Flow: traverses the graph and returns next available FlowGraphNode.name for processing
in case all nodes are blocked - blocks by sleeping
in case all nodes have been yielded for processing - throws StopIteration exception
in case any node has failed - throw StopIteration exception
"""
def _next_iteration():
if len(self.yielded) == len(self):
# all of the nodes have been yielded for processing
raise StopIteration()
for name in self._dict:
if self.is_step_failed(name):
# one of the steps has failed
# thus, marking all flow as failed
raise StopIteration()
if not self.is_step_unblocked(name) or name in self.yielded:
continue
self.yielded.append(name)
return name
return None
next_step_name = _next_iteration()
while next_step_name is None:
# at this point, there are Steps that are blocked, and we must wait for them to become available
time.sleep(5) # 5 seconds
next_step_name = self.next()
return next_step_name
def __eq__(self, other):
return self._dict == other._dict
def __contains__(self, item):
return item in self._dict
def enlist(self, step_exec, dependent_on_names):
assert isinstance(step_exec, StepExecutor)
return self.append(step_exec.step_name, dependent_on_names, step_exec.main_actionset.actions,
step_exec.pre_actionset.actions, step_exec.post_actionset.actions, step_exec.skip)
def append(self, name, dependent_on_names, main_action, pre_actions=None, post_actions=None, skip=False):
""" method appends a new Node to the Graph,
validates the input for non-existent references
:return self to allow chained *append*
"""
assert isinstance(dependent_on_names, list), \
'dependent_on_names must be either a list of string or an empty list'
assert name not in [STEP_NAME_START, STEP_NAME_FINISH], \
'step names [{0}, {1}] are reserved.'.format(STEP_NAME_START, STEP_NAME_FINISH)
def _find_non_existent(names):
non_existent = list()
for name in names:
if name in self:
continue
non_existent.append(name)
return non_existent
if _find_non_existent(dependent_on_names):
raise GraphError('Step {0} from Flow {1} is dependent on a non-existent Step {2}'
.format(name, self.flow_name, dependent_on_names))
node = FlowGraphNode(name, StepExecutor(step_name=name,
main_action=main_action,
pre_actions=pre_actions,
post_actions=post_actions,
skip=skip))
# link newly inserted node with the dependent_on nodes
for dependent_on_name in dependent_on_names:
self[dependent_on_name]._next.append(node)
node._prev.append(self[dependent_on_name])
self._dict[name] = node
# return *self* to allow chained *append*
return self
def all_dependant_steps(self, step_name):
"""
:param step_name: name of the step to inspect
:return: list of all step names, that are dependent on current step
"""
dependent_on = list()
for child_node in self[step_name]._next:
dependent_on.append(child_node.step_name)
dependent_on.extend(self.all_dependant_steps(child_node.step_name))
return dependent_on
def is_step_unblocked(self, step_name):
"""
:param step_name: name of the step to inspect
:return: True if the step has no pending dependencies and is ready for processing; False otherwise
"""
is_unblocked = True
for prev_node in self[step_name]._prev:
if prev_node.step_executor and not prev_node.step_executor.is_complete:
is_unblocked = False
return is_unblocked
def is_step_failed(self, step_name):
"""
:param step_name: name of the step to inspect
:return: True if the step has failed (either in STATE_INVALID or STATE_CANCELED); False otherwise
"""
node = self[step_name]
return node.step_entry and node.step_entry.is_failed
def set_context(self, context, **kwargs):
super(FlowGraph, self).set_context(context, **kwargs)
self.flow_dao = FlowDao(self.logger)
try:
# fetch existing Flow from the DB
db_key = [self.flow_name, self.context.timeperiod]
flow_entry = self.flow_dao.get_one(db_key)
except LookupError:
# no flow record for given key was present in the database
flow_entry = Flow()
flow_entry.flow_name = self.flow_name
flow_entry.timeperiod = self.context.timeperiod
flow_entry.created_at = datetime.utcnow()
flow_entry.state = STATE_EMBRYO
self.flow_dao.update(flow_entry)
self.context.flow_entry = flow_entry
def get_logger(self):
return get_flow_logger(self.flow_name, self.settings)
@valid_context
def clear_steps(self):
""" method purges all steps related to given flow from the DB """
assert self.context.flow_entry is not None
step_dao = StepDao(self.logger)
step_dao.remove_by_flow_id(self.context.flow_entry.db_id)
@valid_context
def load_steps(self):
""" method:
1. loads all steps
2. filters out successful and updates GraphNodes and self.yielded list accordingly
3. removes failed steps from the DB
"""
assert self.context.flow_entry is not None
step_dao = StepDao(self.logger)
steps = step_dao.get_all_by_flow_id(self.context.flow_entry.db_id)
for s in steps:
assert isinstance(s, Step)
if s.is_processed:
self[s.step_name].step_entry = s
self.yielded.append(s.step_name)
else:
step_dao.remove(s.key)
@valid_context
def mark_start(self):
""" performs flow start-up, such as db and context updates """
self.context.flow_entry.started_at = datetime.utcnow()
self.context.flow_entry.state = STATE_IN_PROGRESS
self.flow_dao.update(self.context.flow_entry)
# enable log recording into DB
self.log_recording_handler = LogRecordingHandler(self.get_logger(), self.context.flow_entry.db_id)
self.log_recording_handler.attach()
@valid_context
def _mark_finish(self, state):
self.context.flow_entry.finished_at = datetime.utcnow()
self.context.flow_entry.state = state
self.flow_dao.update(self.context.flow_entry)
if self.log_recording_handler:
self.log_recording_handler.detach()
def mark_failure(self):
""" perform flow post-failure activities, such as db update """
self._mark_finish(STATE_INVALID)
def mark_success(self):
""" perform activities in case of the flow successful completion """
self._mark_finish(STATE_PROCESSED)
| {
"repo_name": "mushkevych/synergy_flow",
"path": "flow/core/flow_graph.py",
"copies": "1",
"size": "8952",
"license": "bsd-3-clause",
"hash": 7261558684651905000,
"line_mean": 37.0936170213,
"line_max": 111,
"alpha_frac": 0.6079088472,
"autogenerated": false,
"ratio": 4.083941605839416,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5191850453039416,
"avg_score": null,
"num_lines": null
} |
__author__ = 'Bohdan Mushkevych'
import time
from flow.core.abstract_action import AbstractAction
class SleepAction(AbstractAction):
def __init__(self, seconds):
super(SleepAction, self).__init__('Sleep Action')
self.seconds = seconds
def run(self, execution_cluster):
time.sleep(self.seconds)
class ShellCommandAction(AbstractAction):
def __init__(self, shell_command):
super(ShellCommandAction, self).__init__('Shell Command Action')
self.shell_command = shell_command
def run(self, execution_cluster):
execution_cluster.run_shell_command(self.shell_command)
class IdentityAction(AbstractAction):
""" this class is intended to be used by Unit Tests """
def __init__(self):
super(IdentityAction, self).__init__('Identity Action')
def run(self, execution_cluster):
self.logger.info('identity action: *do* completed')
class FailureAction(AbstractAction):
""" this class is intended to be used by Unit Tests """
def __init__(self):
super(FailureAction, self).__init__('Failure Action')
def run(self, execution_cluster):
raise UserWarning('failure action: raising exception')
class PigAction(AbstractAction):
""" executes a pig script on the given cluster """
def __init__(self, uri_script, **kwargs):
super(PigAction, self).__init__('Pig Action', kwargs)
self.uri_script = uri_script
def run(self, execution_cluster):
is_successful = execution_cluster.run_pig_step(
uri_script=self.uri_script,
start_timeperiod=self.start_timeperiod,
end_timeperiod=self.end_timeperiod,
timeperiod=self.timeperiod,
**self.kwargs)
if not is_successful:
raise UserWarning('Pig Action failed on {0}'.format(self.uri_script))
class SparkAction(AbstractAction):
""" executes a spark script on the given cluster """
def __init__(self, uri_script, language, **kwargs):
super(SparkAction, self).__init__('Spark Action', kwargs)
self.uri_script = uri_script
self.language = language
def run(self, execution_cluster):
is_successful = execution_cluster.run_spark_step(
uri_script=self.uri_script,
language=self.language,
**self.kwargs)
if not is_successful:
raise UserWarning('Spark Action failed on {0}'.format(self.uri_script))
| {
"repo_name": "mushkevych/synergy_flow",
"path": "flow/core/simple_actions.py",
"copies": "1",
"size": "2455",
"license": "bsd-3-clause",
"hash": 1915457286382317300,
"line_mean": 32.6301369863,
"line_max": 83,
"alpha_frac": 0.6476578411,
"autogenerated": false,
"ratio": 4.078073089700997,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0003301353952874167,
"num_lines": 73
} |
__author__ = 'Bohdan Mushkevych'
import time
import datetime
import unittest
from db.model.raw_data import RawData
class TestRawData(unittest.TestCase):
def setUp(self):
self.obj = RawData()
def tearDown(self):
del self.obj
def test_key(self):
domain_name = 'test_name'
timestamp = time.time()
session_id = 'session_xxx_yyy'
self.obj.key = (domain_name, timestamp, session_id)
assert self.obj.key[0] == domain_name
assert self.obj.key[1] == datetime.datetime.fromtimestamp(timestamp)
assert self.obj.key[2] == session_id
def test_session_id(self):
value = 'value_1234567890'
self.obj.session_id = value
assert self.obj.session_id == value
def test_os(self):
value = 'Windows MS PS 7.0.0.0.1.1.2'
self.obj.os = value
assert self.obj.os == value
def test_browser(self):
br_type = 'FireFox'
version = '3.4.5.6.7.8.9'
self.obj.browser = br_type + version
assert self.obj.browser == br_type + version
def test_ip(self):
value = '100.100.200.200'
self.obj.ip = value
assert self.obj.ip == value
def test_screen_res(self):
value_x = 1080
value_y = 980
self.obj.screen_res = (value_x, value_y)
assert self.obj.screen_x == value_x
assert self.obj.screen_y == value_y
def test_language(self):
value = 'ca-uk'
self.obj.language = value
assert self.obj.language == value
def test_country(self):
value = 'ca'
self.obj.country = value
assert self.obj.country == value
if __name__ == '__main__':
unittest.main()
| {
"repo_name": "eggsandbeer/scheduler",
"path": "tests/test_raw_data.py",
"copies": "1",
"size": "1719",
"license": "bsd-3-clause",
"hash": -7735843768557255000,
"line_mean": 25.4461538462,
"line_max": 76,
"alpha_frac": 0.5828970332,
"autogenerated": false,
"ratio": 3.403960396039604,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.44868574292396035,
"avg_score": null,
"num_lines": null
} |
__author__ = 'Bohdan Mushkevych'
import time
import googleapiclient.discovery
from flow.core.abstract_cluster import AbstractCluster, ClusterError
from flow.core.gcp_filesystem import GcpFilesystem
from flow.core.gcp_credentials import gcp_credentials
# `https://cloud.google.com/dataproc/docs/reference/rest/v1/projects.regions.clusters#ClusterStatus`_
CLUSTER_STATE_UNKNOWN = 'UNKNOWN'
CLUSTER_STATE_CREATING = 'CREATING'
CLUSTER_STATE_RUNNING = 'RUNNING'
CLUSTER_STATE_ERROR = 'ERROR'
CLUSTER_STATE_DELETING = 'DELETING'
CLUSTER_STATE_UPDATING = 'UPDATING'
OPERATION_STATE_PENDING = 'PENDING'
OPERATION_STATE_SETUP_DONE = 'SETUP_DONE'
# `https://cloud.google.com/dataproc/docs/concepts/jobs/life-of-a-job`_
JOB_STATE_PENDING = 'PENDING'
JOB_STATE_RUNNING = 'RUNNING'
JOB_STATE_QUEUED = 'QUEUED'
JOB_STATE_DONE = 'DONE'
JOB_STATE_ERROR = 'ERROR'
class GcpCluster(AbstractCluster):
""" implementation of the Google Cloud Platform Dataproc API """
def __init__(self, name, context, **kwargs):
super(GcpCluster, self).__init__(name, context, kwargs=kwargs)
self._filesystem = GcpFilesystem(self.logger, context, **kwargs)
service_account_file_uri = self.context.settings.get('gcp_service_account_file')
credentials = gcp_credentials(service_account_file_uri)
self.dataproc = googleapiclient.discovery.build('dataproc', 'v1', credentials=credentials)
self.cluster_details = None
self.project_id = context.settings['gcp_project_id']
self.cluster_name = context.settings['gcp_cluster_name']
self.cluster_region = context.settings['gcp_cluster_region']
self.cluster_zone = context.settings['gcp_cluster_zone']
@property
def filesystem(self):
return self._filesystem
def _run_step(self, job_details):
if not self.cluster_details:
raise ClusterError('EMR Cluster {0} is not launched'.format(self.cluster_name))
result = self.dataproc.projects().regions().jobs().submit(
projectId=self.project_id,
region=self.cluster_region,
body=job_details).execute()
job_id = result['reference']['jobId']
self.logger.info('Submitted job ID {0}. Waiting for completion'.format(job_id))
return self._poll_step(job_id)
def _poll_step(self, job_id):
details = 'NA'
state = JOB_STATE_PENDING
while state in [OPERATION_STATE_SETUP_DONE, JOB_STATE_PENDING, JOB_STATE_RUNNING, JOB_STATE_QUEUED]:
result = self.dataproc.projects().regions().jobs().get(
projectId=self.project_id,
region=self.cluster_region,
jobId=job_id).execute()
state = result['status']['state']
if 'details' in result['status']:
details = result['status']['details']
if state == JOB_STATE_ERROR:
raise ClusterError('Gcp Job {0} failed: {1}'.format(job_id, details))
elif state == JOB_STATE_DONE:
self.logger.info('Gcp Job {0} has completed.')
else:
self.logger.warning('Unknown state {0} during Gcp Job {1} execution'.format(state, job_id))
return state
def run_pig_step(self, uri_script, libs=None, **kwargs):
# `https://cloud.google.com/dataproc/docs/reference/rest/v1beta2/PigJob`_
job_details = {
'projectId': self.project_id,
'job': {
'placement': {
'clusterName': self.cluster_name
},
'pigJob': {
'queryFileUri': 'gs://{}/{}'.format(self.context.settings['gcp_code_bucket'], uri_script)
}
}
}
if kwargs:
job_details['job']['pigJob']['scriptVariables'] = '{}'.format(kwargs)
if libs:
gs_libs = ['gs://{}/{}'.format(self.context.settings['gcp_code_bucket'], x) for x in libs]
job_details['job']['pigJob']['jarFileUris'] = '{}'.format(gs_libs)
return self._run_step(job_details)
def run_spark_step(self, uri_script, language, libs=None, **kwargs):
# `https://cloud.google.com/dataproc/docs/reference/rest/v1beta2/PySparkJob`_
job_details = {
'projectId': self.project_id,
'job': {
'placement': {
'clusterName': self.cluster_name
},
'pysparkJob': {
'mainPythonFileUri': 'gs://{}/{}'.format(self.context.settings['gcp_code_bucket'], uri_script)
}
}
}
if libs:
gs_libs = ['gs://{}/{}'.format(self.context.settings['gcp_code_bucket'], x) for x in libs]
job_details['job']['pysparkJob']['pythonFileUris'] = '{}'.format(gs_libs)
return self._run_step(job_details)
def run_hadoop_step(self, uri_script, **kwargs):
# `https://cloud.google.com/dataproc/docs/reference/rest/v1beta2/HadoopJob`_
raise NotImplementedError('Implement run_hadoop_step for the Gcp cluster')
def run_shell_command(self, uri_script, **kwargs):
raise NotImplementedError('TODO: implement shell command')
def _launch(self):
zone_uri = \
'https://www.googleapis.com/compute/v1/projects/{}/zones/{}'.format(self.project_id, self.cluster_zone)
cluster_data = {
'projectId': self.project_id,
'clusterName': self.cluster_name,
'config': {
'gceClusterConfig': {
'zoneUri': zone_uri
},
'masterConfig': {
'numInstances': 1,
'machineTypeUri': 'n1-standard-1'
},
'workerConfig': {
'numInstances': 2,
'machineTypeUri': 'n1-standard-1'
}
}
}
result = self.dataproc.projects().regions().clusters().create(
projectId=self.project_id,
region=self.cluster_region,
body=cluster_data).execute()
if result['metadata']['status']['state'] in [CLUSTER_STATE_CREATING, CLUSTER_STATE_RUNNING,
CLUSTER_STATE_UPDATING, OPERATION_STATE_PENDING]:
self.logger.info('Launch request successful')
else:
self.logger.warning('Cluster {0} entered unknown state {1}'.
format(self.cluster_name, result['metadata']['status']['state']))
def _get_cluster(self):
try:
result = self.dataproc.projects().regions().clusters().get(
projectId=self.project_id,
region=self.cluster_region,
clusterName=self.cluster_name).execute()
return result
except:
return None
def _wait_for_cluster(self):
cluster = self._get_cluster()
while cluster:
if cluster['status']['state'] == CLUSTER_STATE_ERROR:
raise ClusterError('Cluster {0} creation error: {1}'.
format(self.cluster_name, cluster['status']['details']))
if cluster['status']['state'] == CLUSTER_STATE_RUNNING:
self.logger.info('Cluster {0} is running'.format(self.cluster_name))
break
else:
time.sleep(5)
cluster = self._get_cluster()
return cluster
def launch(self):
self.logger.info('Launching Gcp Cluster: {0} {{'.format(self.cluster_name))
if not self._get_cluster():
self._launch()
self.cluster_details = self._wait_for_cluster()
self.logger.info('}')
def terminate(self):
self.logger.info('Terminating Gcp Cluster {')
result = self.dataproc.projects().regions().clusters().delete(
projectId=self.project_id,
region=self.cluster_region,
clusterName=self.cluster_name).execute()
if result['metadata']['status']['state'] in [CLUSTER_STATE_DELETING, CLUSTER_STATE_UNKNOWN,
OPERATION_STATE_PENDING]:
self.cluster_details = None
self.logger.info('Termination request successful')
else:
self.logger.warning('Cluster {0} entered unknown state {1}'.
format(self.cluster_name, result['metadata']['status']['state']))
self.logger.info('}')
| {
"repo_name": "mushkevych/synergy_flow",
"path": "flow/core/gcp_cluster.py",
"copies": "1",
"size": "8523",
"license": "bsd-3-clause",
"hash": -7292146590968090000,
"line_mean": 39.3933649289,
"line_max": 115,
"alpha_frac": 0.5750322656,
"autogenerated": false,
"ratio": 4.029787234042553,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5104819499642553,
"avg_score": null,
"num_lines": null
} |
__author__ = 'Bohdan Mushkevych'
import time
import os
import psutil
from synergy.system.repeat_timer import RepeatTimer
from synergy.conf import settings
class FootprintCalculator(object):
def __init__(self):
self.pid = os.getpid()
def group(self, number):
""" method formats number and inserts thousands separators """
s = str(number)
groups = []
while s and s[-1].isdigit():
groups.append(s[-3:])
s = s[:-3]
return s + '\''.join(reversed(groups))
@property
def document(self):
ps = psutil.Process(self.pid)
return {'memory_rss': self.group(ps.get_memory_info()[0]),
'memory_vms': self.group(ps.get_memory_info()[1]),
'cpu_utilization': '%02d' % ps.get_cpu_percent(),
'mem_virtual_free': self.group(psutil.virtual_memory().free),
'mem_swap_free': self.group(psutil.swap_memory().free)}
def get_snapshot(self):
resp = 'Footprint: RSS={memory_rss} VMS={memory_vms} CPU={cpu_utilization}; ' \
'Available: PHYS={mem_virtual_free} VIRT={mem_swap_free}'.format(**self.document)
return resp
class Tracker(object):
def __init__(self, name):
self.name = name
self.per_24h = 0
self.per_tick = 0
def increment(self, delta=1):
self.per_24h += delta
self.per_tick += delta
def reset_tick(self):
self.per_tick = 0
def reset_24h(self):
self.per_24h = 0
class TrackerPair(object):
def __init__(self, name, success='Success', failure='Failure'):
self.name = name
self.success = Tracker(success)
self.failure = Tracker(failure)
def increment_success(self, delta=1):
self.success.increment(delta)
def increment_failure(self, delta=1):
self.failure.increment(delta)
def reset_tick(self):
self.success.reset_tick()
self.failure.reset_tick()
def reset_24h(self):
self.success.reset_24h()
self.failure.reset_24h()
def to_string(self, tick_interval_seconds, show_header=True):
header = self.name + ' : ' + self.success.name + '/' + self.failure.name + '.' if show_header else ''
return header + 'In last {0:d} seconds: {1:d}/{2:d}. In last 24 hours: {3:d}/{4:d}'.format(
tick_interval_seconds,
self.success.per_tick,
self.failure.per_tick,
self.success.per_24h,
self.failure.per_24h)
class TickerThread(object):
SECONDS_IN_24_HOURS = 86400
TICKS_BETWEEN_FOOTPRINTS = 10
def __init__(self, logger):
self.logger = logger
self.trackers = dict()
self.interval = settings.settings['perf_ticker_interval']
self.mark_24_hours = time.time()
self.mark_footprint = time.time()
self.footprint = FootprintCalculator()
self.timer = RepeatTimer(self.interval, self._run_tick_thread)
def add_tracker(self, tracker):
self.trackers[tracker.name] = tracker
def get_tracker(self, name):
return self.trackers[name]
def start(self):
self.timer.start()
def cancel(self):
self.timer.cancel()
def is_alive(self):
return self.timer.is_alive()
def _print_footprint(self):
if time.time() - self.mark_footprint > self.TICKS_BETWEEN_FOOTPRINTS * self.interval:
self.logger.info(self.footprint.get_snapshot())
self.mark_footprint = time.time()
def _run_tick_thread(self):
self._print_footprint()
current_time = time.time()
do_24h_reset = current_time - self.mark_24_hours > self.SECONDS_IN_24_HOURS
if do_24h_reset:
self.mark_24_hours = current_time
tracker_outputs = []
for tracker_name, tracker in self.trackers.items():
tracker_outputs.append(tracker.to_string(self.interval))
tracker.reset_tick()
if do_24h_reset:
tracker.reset_24h()
self.logger.info('\n'.join(tracker_outputs))
class SimpleTracker(TickerThread):
TRACKER_PERFORMANCE = 'Performance'
def __init__(self, logger):
super(SimpleTracker, self).__init__(logger)
self.add_tracker(TrackerPair(self.TRACKER_PERFORMANCE))
@property
def tracker(self):
return self.get_tracker(self.TRACKER_PERFORMANCE)
class SessionPerformanceTracker(TickerThread):
TRACKER_INSERT = 'Insert'
TRACKER_UPDATE = 'Update'
def __init__(self, logger):
super(SessionPerformanceTracker, self).__init__(logger)
self.add_tracker(TrackerPair(self.TRACKER_INSERT))
self.add_tracker(TrackerPair(self.TRACKER_UPDATE))
@property
def insert(self):
return self.get_tracker(self.TRACKER_INSERT)
@property
def update(self):
return self.get_tracker(self.TRACKER_UPDATE)
class UowAwareTracker(SimpleTracker):
STATE_IDLE = 'state_idle'
STATE_PROCESSING = 'state_processing'
def __init__(self, logger):
super(UowAwareTracker, self).__init__(logger)
self.state = self.STATE_IDLE
self.per_job = 0
self.uow = None
self.state_triggered_at = time.time()
def _run_tick_thread(self):
super(UowAwareTracker, self)._run_tick_thread()
if self.state == self.STATE_PROCESSING:
msg = 'State: {0} for {1} sec; {2} in this uow;'.\
format(self.state, time.time() - self.state_triggered_at, self.per_job)
else:
msg = 'State: {0} for {1} sec;'.format(self.state, time.time() - self.state_triggered_at)
self.logger.info(msg)
def increment(self):
self.tracker.increment_success()
self.per_job += 1
def start_uow(self, uow):
self.state = self.STATE_PROCESSING
self.uow = uow
self.state_triggered_at = time.time()
def finish_uow(self):
self.logger.info('Success: unit_of_work {0} in timeperiod {1}; processed {2} entries in {3} seconds'.
format(self.uow.db_id, self.uow.timeperiod,
self.per_job, time.time() - self.state_triggered_at))
self.cancel_uow()
def cancel_uow(self):
self.state = self.STATE_IDLE
self.uow = None
self.state_triggered_at = time.time()
self.per_job = 0
| {
"repo_name": "eggsandbeer/scheduler",
"path": "synergy/system/performance_tracker.py",
"copies": "1",
"size": "6404",
"license": "bsd-3-clause",
"hash": -1617929295930537700,
"line_mean": 29.7884615385,
"line_max": 109,
"alpha_frac": 0.5993129294,
"autogenerated": false,
"ratio": 3.526431718061674,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4625744647461674,
"avg_score": null,
"num_lines": null
} |
__author__ = 'Bohdan Mushkevych'
import time
import os
import psutil
from system.repeat_timer import RepeatTimer
from settings import settings
class FootprintCalculator(object):
def __init__(self):
self.pid = os.getpid()
@property
def document(self):
ps = psutil.Process(self.pid)
# '{:,}'.format(number) returns a string with coma as a thousand-separator
return {'memory_rss': '{:,}'.format(ps.memory_info()[0]),
'memory_vms': '{:,}'.format(ps.memory_info()[1]),
'cpu_utilization': '{0:02.0f}'.format(ps.cpu_percent()),
'mem_virtual_free': '{:,}'.format(psutil.virtual_memory().free),
'mem_swap_free': '{:,}'.format(psutil.swap_memory().free)}
def get_snapshot(self):
resp = 'Footprint: RSS={memory_rss} VMS={memory_vms} CPU={cpu_utilization}; ' \
'Available: PHYS={mem_virtual_free} VIRT={mem_swap_free}'.format(**self.document)
return resp
class Tracker(object):
def __init__(self, name):
self.name = name
self.per_24h = 0
self.per_tick = 0
def increment(self, delta=1):
self.per_24h += delta
self.per_tick += delta
def reset_tick(self):
self.per_tick = 0
def reset_24h(self):
self.per_24h = 0
class TrackerPair(object):
def __init__(self, name, success='Success', failure='Failure'):
self.name = name
self.success = Tracker(success)
self.failure = Tracker(failure)
def increment_success(self, delta=1):
self.success.increment(delta)
def increment_failure(self, delta=1):
self.failure.increment(delta)
def reset_tick(self):
self.success.reset_tick()
self.failure.reset_tick()
def reset_24h(self):
self.success.reset_24h()
self.failure.reset_24h()
def to_string(self, tick_interval_seconds, show_header=True):
header = self.name + ' : ' + self.success.name + '/' + self.failure.name + '.' if show_header else ''
return header + 'In last {0:d} seconds: {1:d}/{2:d}. In last 24 hours: {3:d}/{4:d}'.format(
tick_interval_seconds,
self.success.per_tick,
self.failure.per_tick,
self.success.per_24h,
self.failure.per_24h)
class TickerThread(object):
SECONDS_IN_24_HOURS = 86400
TICKS_BETWEEN_FOOTPRINTS = 10
def __init__(self, logger):
self.logger = logger
self.trackers = dict()
self.interval = settings['perf_ticker_interval']
self.mark_24_hours = time.time()
self.mark_footprint = time.time()
self.footprint = FootprintCalculator()
self.timer = RepeatTimer(self.interval, self._run_tick_thread, daemonic=True)
def add_tracker(self, tracker):
self.trackers[tracker.name] = tracker
def get_tracker(self, name):
return self.trackers[name]
def start(self):
self.timer.start()
def cancel(self):
self.timer.cancel()
def is_alive(self):
return self.timer.is_alive()
def _print_footprint(self):
if time.time() - self.mark_footprint > self.TICKS_BETWEEN_FOOTPRINTS * self.interval:
self.logger.info(self.footprint.get_snapshot())
self.mark_footprint = time.time()
def _run_tick_thread(self):
self._print_footprint()
current_time = time.time()
do_24h_reset = current_time - self.mark_24_hours > self.SECONDS_IN_24_HOURS
if do_24h_reset:
self.mark_24_hours = current_time
tracker_outputs = []
for tracker_name, tracker in self.trackers.items():
tracker_outputs.append(tracker.to_string(self.interval))
tracker.reset_tick()
if do_24h_reset:
tracker.reset_24h()
self.logger.info('\n'.join(tracker_outputs))
class SimpleTracker(TickerThread):
TRACKER_PERFORMANCE = 'Performance'
def __init__(self, logger):
super(SimpleTracker, self).__init__(logger)
self.add_tracker(TrackerPair(self.TRACKER_PERFORMANCE))
@property
def tracker(self):
return self.get_tracker(self.TRACKER_PERFORMANCE)
| {
"repo_name": "mushkevych/launch.py",
"path": "system/performance_tracker.py",
"copies": "1",
"size": "4223",
"license": "bsd-3-clause",
"hash": -8386667933597576000,
"line_mean": 29.381294964,
"line_max": 109,
"alpha_frac": 0.6017049491,
"autogenerated": false,
"ratio": 3.5133111480865225,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9611443123720971,
"avg_score": 0.0007145946931103414,
"num_lines": 139
} |
__author__ = 'Bohdan Mushkevych'
import time
import unittest
from datetime import datetime
from system import repeat_timer
class TestRepeatTimer(unittest.TestCase):
INTERVAL = 3
def make_method_yes(self, initial_multiplication=1):
# the only way to implement nonlocal closure variables in Python 2.X
cycle = {'index': initial_multiplication}
def method_yes(start_datetime, seconds):
delta = datetime.utcnow() - start_datetime
assert delta.seconds == cycle['index'] * seconds
cycle['index'] += 1
return method_yes
def method_no(self, start_datetime, seconds):
raise AssertionError('Assertion failed as NO was executed with parameters {0} {1}'.
format(str(start_datetime), seconds))
def method_checkpoint(self, start_datetime, seconds):
print('Entering method checkpoint with parameters {0} {1}'.format(str(start_datetime), seconds))
delta = datetime.utcnow() - start_datetime
if delta.seconds != seconds:
raise AssertionError('Assertion failed by {0} {1}'.format(str(delta), seconds))
def test_normal_workflow(self):
self.obj = repeat_timer.RepeatTimer(TestRepeatTimer.INTERVAL,
self.method_checkpoint,
args=[datetime.utcnow(), TestRepeatTimer.INTERVAL])
self.obj.start()
time.sleep(TestRepeatTimer.INTERVAL)
self.obj.cancel()
assert True
def test_cancellation(self):
self.obj = repeat_timer.RepeatTimer(TestRepeatTimer.INTERVAL,
self.method_no,
args=[datetime.utcnow(), 0])
self.obj.start()
self.obj.cancel()
time.sleep(TestRepeatTimer.INTERVAL)
assert True
def test_trigger(self):
self.obj = repeat_timer.RepeatTimer(TestRepeatTimer.INTERVAL,
self.make_method_yes(),
args=[datetime.utcnow(), 0])
self.obj.start()
self.obj.trigger()
self.obj.cancel()
time.sleep(TestRepeatTimer.INTERVAL)
assert True
def test_trigger_with_continuation(self):
self.obj = repeat_timer.RepeatTimer(TestRepeatTimer.INTERVAL - 1,
self.make_method_yes(initial_multiplication=0),
args=[datetime.utcnow(), TestRepeatTimer.INTERVAL - 1])
self.obj.start()
self.obj.trigger()
time.sleep(TestRepeatTimer.INTERVAL)
self.obj.cancel()
assert True
if __name__ == '__main__':
unittest.main()
| {
"repo_name": "mushkevych/launch.py",
"path": "tests/test_repeat_timer.py",
"copies": "1",
"size": "2777",
"license": "bsd-3-clause",
"hash": 7291716159054760000,
"line_mean": 37.0410958904,
"line_max": 104,
"alpha_frac": 0.5729204177,
"autogenerated": false,
"ratio": 4.60530679933665,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.567822721703665,
"avg_score": null,
"num_lines": null
} |
__author__ = 'Bohdan Mushkevych'
import time
from psutil import TimeoutExpired
from synergy.db.model import unit_of_work
from synergy.workers.abstract_uow_aware_worker import AbstractUowAwareWorker
RETURN_CODE_CANCEL_UOW = 987654321
class AbstractCliWorker(AbstractUowAwareWorker):
""" Module contains common logic for Command Line Callers.
It executes shell command and updates unit_of_work base on command's return code """
def __init__(self, process_name):
super(AbstractCliWorker, self).__init__(process_name)
self.cli_process = None
def __del__(self):
super(AbstractCliWorker, self).__del__()
def _start_process(self, start_timeperiod, end_timeperiod, arguments):
raise NotImplementedError('method _start_process must be implemented by %s' % self.__class__.__name__)
def _poll_process(self):
""" between death of a process and its actual termination lies poorly documented requirement -
<purging process' io pipes and reading exit status>.
this can be done either by os.wait() or process.wait()
:return tuple (boolean: alive, int: return_code) """
try:
self.logger.warn(self.cli_process.stderr.read())
self.logger.info(self.cli_process.stdout.read())
return_code = self.cli_process.wait(timeout=0.01)
if return_code is None:
# process is already terminated
self.logger.info('Process %s is terminated' % self.process_name)
else:
# process is terminated; possibly by OS
self.logger.info('Process %s got terminated. Cleaning up' % self.process_name)
self.cli_process = None
return False, return_code
except TimeoutExpired:
# process is alive and OK
return True, None
except Exception:
self.logger.error('Exception on polling: %s' % self.process_name, exc_info=True)
return False, 999
def _process_uow(self, uow):
self._start_process(uow.start_timeperiod, uow.end_timeperiod, uow.arguments)
code = None
alive = True
while alive:
alive, code = self._poll_process()
time.sleep(0.1)
self.logger.info('Command Line Command return code is %r' % code)
if code == 0:
return 0, unit_of_work.STATE_PROCESSED
elif code == RETURN_CODE_CANCEL_UOW:
return 0, unit_of_work.STATE_CANCELED
else:
raise UserWarning('Command Line Command return code is not 0 but %r' % code)
| {
"repo_name": "eggsandbeer/scheduler",
"path": "workers/abstract_cli_worker.py",
"copies": "1",
"size": "2617",
"license": "bsd-3-clause",
"hash": 2670435129854330000,
"line_mean": 39.890625,
"line_max": 110,
"alpha_frac": 0.6289644631,
"autogenerated": false,
"ratio": 4.057364341085271,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5186328804185271,
"avg_score": null,
"num_lines": null
} |
__author__ = 'Bohdan Mushkevych'
import time
import boto3
from flow.core.abstract_cluster import AbstractCluster, ClusterError
from flow.core.s3_filesystem import S3Filesystem
# `http://boto3.readthedocs.io/en/latest/reference/services/emr.html#EMR.Client.describe_cluster`_
CLUSTER_STATE_TERMINATED_WITH_ERRORS = 'TERMINATED_WITH_ERRORS'
CLUSTER_STATE_TERMINATED = 'TERMINATED'
CLUSTER_STATE_TERMINATING = 'TERMINATING'
CLUSTER_STATE_WAITING = 'WAITING'
CLUSTER_STATE_RUNNING = 'RUNNING'
CLUSTER_STATE_BOOTSTRAPPING = 'BOOTSTRAPPING'
CLUSTER_STATE_STARTING = 'STARTING'
# `http://boto3.readthedocs.io/en/latest/reference/services/emr.html#EMR.Client.describe_step`_
STEP_STATE_PENDING = 'PENDING'
STEP_STATE_CANCEL_PENDING = 'CANCEL_PENDING'
STEP_STATE_RUNNING = 'RUNNING'
STEP_STATE_COMPLETED = 'COMPLETED'
STEP_STATE_CANCELLED = 'CANCELLED'
STEP_STATE_FAILED = 'FAILED'
STEP_STATE_INTERRUPTED = 'INTERRUPTED'
class EmrCluster(AbstractCluster):
""" implementation of the abstract API for the case of AWS EMR """
def __init__(self, name, context, **kwargs):
super(EmrCluster, self).__init__(name, context, **kwargs)
self._filesystem = S3Filesystem(self.logger, context, **kwargs)
self.jobflow_id = None # it is both ClusterId and the JobflowId
self.client_b3 = boto3.client(service_name='emr',
region_name=context.settings['aws_cluster_region'],
aws_access_key_id=context.settings['aws_access_key_id'],
aws_secret_access_key=context.settings['aws_secret_access_key'])
@property
def filesystem(self):
return self._filesystem
def _poll_step(self, step_id):
""" method polls the state for given step_id and awaits its completion """
def _current_state():
step = self.client_b3.describe_step(ClusterId=self.jobflow_id, StepId=step_id)
return step['Step']['Status']['State']
state = _current_state()
while state in [STEP_STATE_PENDING, STEP_STATE_RUNNING]:
# Job flow step is being spawned. Idle and recheck the status.
time.sleep(20.0)
state = _current_state()
if state in [STEP_STATE_CANCELLED, STEP_STATE_INTERRUPTED, STEP_STATE_CANCEL_PENDING, STEP_STATE_FAILED]:
raise ClusterError('EMR Step {0} failed'.format(step_id))
elif state == STEP_STATE_COMPLETED:
self.logger.info('EMR Step {0} has completed'.format(step_id))
else:
self.logger.warning('Unknown state {0} during EMR Step {1} execution'.format(state, step_id))
return state
def run_pig_step(self, uri_script, **kwargs):
"""
method starts a Pig step on a cluster and monitors its execution
:raise EmrLauncherError: in case the cluster is not launched
:return: step state or None if the step failed
"""
# `https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-commandrunner.html`_
# `http://boto3.readthedocs.io/en/latest/reference/services/emr.html#EMR.Client.add_job_flow_steps`_
if not self.jobflow_id:
raise ClusterError('EMR Cluster {0} is not launched'.format(self.name))
self.logger.info('Pig Script Step {')
try:
step = {
'Name': 'SynergyPigStep',
'ActionOnFailure': 'CONTINUE',
'HadoopJarStep': {
'Jar': 'command-runner.jar',
'Args': ['pig-script', '--run-pig-script', '--args', '-f', uri_script]
}
}
if kwargs:
properties = [{'Key': '{}'.format(k), 'Value': '{}'.format(v)} for k, v in kwargs.items()]
step['HadoopJarStep']['Properties'] = properties
step_args = []
for k, v in kwargs.items():
step_args.append('-p')
step_args.append('{0}={1}'.format(k, v))
step['HadoopJarStep']['Args'].extend(step_args)
step_response = self.client_b3.add_job_flow_steps(JobFlowId=self.jobflow_id, Steps=[step])
step_ids = step_response['StepIds']
assert len(step_ids) == 1
return self._poll_step(step_ids[0])
except ClusterError as e:
self.logger.error('Pig Script Step Error: {0}'.format(e), exc_info=True)
return None
except Exception as e:
self.logger.error('Pig Script Step Unexpected Exception: {0}'.format(e), exc_info=True)
return None
finally:
self.logger.info('}')
def run_spark_step(self, uri_script, language, **kwargs):
# `https://github.com/dev-86/aws-cli/blob/29756ea294aebc7c854b3d9a2b1a56df28637e11/tests/unit/customizations/emr/test_create_cluster_release_label.py`_
# `https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-commandrunner.html`_
# `http://boto3.readthedocs.io/en/latest/reference/services/emr.html#EMR.Client.add_job_flow_steps`_
if not self.jobflow_id:
raise ClusterError('EMR Cluster {0} is not launched'.format(self.name))
self.logger.info('Spark Step {')
try:
step = {
'Name': 'SynergyPysparkStep',
'ActionOnFailure': 'CONTINUE',
'HadoopJarStep': {
'Jar': 'command-runner.jar',
'Args': ['spark-submit', '--deploy-mode', 'cluster', uri_script]
}
}
if kwargs:
properties = [{'Key': '{}'.format(k), 'Value': '{}'.format(v)} for k, v in kwargs.items()]
step['HadoopJarStep']['Properties'] = properties
step_response = self.client_b3.add_job_flow_steps(JobFlowId=self.jobflow_id, Steps=[step])
step_ids = step_response['StepIds']
assert len(step_ids) == 1
return self._poll_step(step_ids[0])
except ClusterError as e:
self.logger.error('Spark Step Error: {0}'.format(e), exc_info=True)
return None
except Exception as e:
self.logger.error('Spark Step Unexpected Exception: {0}'.format(e), exc_info=True)
return None
finally:
self.logger.info('}')
def run_hadoop_step(self, uri_script, **kwargs):
# `https://github.com/dev-86/aws-cli/blob/29756ea294aebc7c854b3d9a2b1a56df28637e11/tests/unit/customizations/emr/test_create_cluster_release_label.py`_
pass
def run_shell_command(self, uri_script, **kwargs):
# `https://github.com/dev-86/aws-cli/blob/29756ea294aebc7c854b3d9a2b1a56df28637e11/tests/unit/customizations/emr/test_create_cluster_release_label.py`_
pass
def _launch(self):
"""
method launches the cluster and returns when the cluster is fully operational
and ready to accept business steps
:see: `http://boto3.readthedocs.io/en/latest/reference/services/emr.html#EMR.Client.add_job_flow_steps`_
"""
self.logger.info('Launching EMR Cluster {0} {{'.format(self.name))
try:
response = self.client_b3.run_job_flow(
Name=self.context.settings['aws_cluster_name'],
ReleaseLabel='emr-5.12.0',
Instances={
'MasterInstanceType': 'm3.xlarge',
'SlaveInstanceType': 'm3.xlarge',
'InstanceCount': 3,
'KeepJobFlowAliveWhenNoSteps': True,
'TerminationProtected': True,
'Ec2KeyName': self.context.settings.get('aws_key_name', ''),
},
BootstrapActions=[
{
'Name': 'Maximize Spark Default Config',
'ScriptBootstrapAction': {
'Path': 's3://support.elasticmapreduce/spark/maximize-spark-default-config',
}
},
],
Applications=[
{
'Name': 'Spark',
},
{
'Name': 'Pig',
},
],
VisibleToAllUsers=True,
JobFlowRole='EMR_EC2_DefaultRole',
ServiceRole='EMR_DefaultRole'
)
self.logger.info('EMR Cluster Initialization Request Successful.')
return response['JobFlowId']
except:
self.logger.error('EMR Cluster failed to launch', exc_info=True)
raise ClusterError('EMR Cluster {0} launch failed'.format(self.name))
finally:
self.logger.info('}')
def _get_cluster(self):
try:
clusters = self.client_b3.list_clusters(ClusterStates=['STARTING', 'BOOTSTRAPPING', 'RUNNING', 'WAITING'])
for cluster in clusters['Clusters']:
if cluster['Name'] != self.context.settings['aws_cluster_name']:
continue
return cluster['Id']
return None
except:
return None
def _wait_for_cluster(self, cluster_id):
""" method polls the state for the cluster and awaits until it is ready to start processing """
def _current_state():
cluster = self.client_b3.describe_cluster(ClusterId=cluster_id)
return cluster['Cluster']['Status']['State']
state = _current_state()
while state in [CLUSTER_STATE_STARTING, CLUSTER_STATE_BOOTSTRAPPING, CLUSTER_STATE_RUNNING]:
# Cluster is being spawned. Idle and recheck the status.
time.sleep(20.0)
state = _current_state()
if state in [CLUSTER_STATE_TERMINATING, CLUSTER_STATE_TERMINATED, CLUSTER_STATE_TERMINATED_WITH_ERRORS]:
raise ClusterError('EMR Cluster {0} launch failed'.format(self.name))
elif state == CLUSTER_STATE_WAITING:
# state WAITING marks readiness to process business steps
cluster = self.client_b3.describe_cluster(ClusterId=cluster_id)
master_dns = cluster['Cluster']['MasterPublicDnsName']
self.logger.info('EMR Cluster Launched Successfully. Master DNS node is {0}'.format(master_dns))
else:
self.logger.warning('Unknown state {0} during EMR Cluster launch'.format(state))
return state
def launch(self):
self.logger.info('Launching EMR Cluster: {0} {{'.format(self.context.settings['aws_cluster_name']))
if self.jobflow_id \
and self._wait_for_cluster(self.jobflow_id) in [CLUSTER_STATE_STARTING, CLUSTER_STATE_BOOTSTRAPPING,
CLUSTER_STATE_RUNNING]:
raise ClusterError('EMR Cluster {0} has already been launched with id {1}. Use it or dispose it.'
.format(self.name, self.jobflow_id))
cluster_id = self._get_cluster()
if cluster_id:
self.logger.info('Reusing existing EMR Cluster: {0} {{'.format(cluster_id))
else:
cluster_id = self._launch()
self._wait_for_cluster(cluster_id)
self.jobflow_id = cluster_id
self.logger.info('}')
def terminate(self):
""" method terminates the cluster """
if not self.jobflow_id:
self.logger.info('No EMR Cluster to stop')
return
self.logger.info('Terminating EMR Cluster {')
try:
self.logger.info('Initiating termination procedure...')
# Disable cluster termination protection
self.client_b3.set_termination_protection(JobFlowIds=[self.jobflow_id], TerminationProtected=False)
self.client_b3.terminate_job_flows(JobFlowIds=[self.jobflow_id])
self.jobflow_id = None
self.logger.info('Termination request successful')
except Exception as e:
self.logger.error('Unexpected Exception: {0}'.format(e), exc_info=True)
finally:
self.logger.info('}')
| {
"repo_name": "mushkevych/synergy_flow",
"path": "flow/core/emr_cluster.py",
"copies": "1",
"size": "12175",
"license": "bsd-3-clause",
"hash": -5344821238485574000,
"line_mean": 42.6379928315,
"line_max": 159,
"alpha_frac": 0.58275154,
"autogenerated": false,
"ratio": 3.879859783301466,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9953278177422135,
"avg_score": 0.0018666291758662444,
"num_lines": 279
} |
__author__ = 'Bohdan Mushkevych'
import unittest
from collections import OrderedDict
from synergy.system import time_helper
from synergy.system.timeperiod_dict import TimeperiodDict
from synergy.system.time_qualifier import *
class TestTimeperiodDict(unittest.TestCase):
def test_identity_translation(self):
fixture = {
QUALIFIER_HOURLY: {'2010123123': '2010123123',
'2010123110': '2010123110',
'2010123100': '2010123100'},
QUALIFIER_DAILY: {'2010123100': '2010123100',
'2010120100': '2010120100'},
QUALIFIER_MONTHLY: {'2010120000': '2010120000',
'2010010000': '2010010000'},
QUALIFIER_YEARLY: {'2010000000': '2010000000',
'2011000000': '2011000000'},
}
for qualifier, f in fixture.items():
d = TimeperiodDict(qualifier, 1)
for key, value in f.items():
self.assertEqual(d._translate_timeperiod(key), value,
msg='failing combination: q={0} fixture={1}:{2} actual={3}'.
format(qualifier, key, value, d._translate_timeperiod(key)))
def test_grouping_translation(self):
fixture = {
QUALIFIER_HOURLY: {'2010123123': '2010123123',
'2010123122': '2010123123',
'2010123110': '2010123110',
'2010123111': '2010123115',
'2010123101': '2010123105',
'2010123100': '2010123105'},
QUALIFIER_DAILY: {'2010123100': '2010123100',
'2010120100': '2010120500',
'2010120600': '2010121000',
'2010123000': '2010123000',
'2010122000': '2010122000'},
QUALIFIER_MONTHLY: {'2010120000': '2010120000',
'2010010000': '2010050000',
'2010100000': '2010100000',
'2010110000': '2010120000'},
}
for qualifier, f in fixture.items():
d = TimeperiodDict(qualifier, 5)
for key, value in f.items():
self.assertEqual(d._translate_timeperiod(key), value,
msg='failing combination: q={0} fixture={1}/{2} actual={3}'.
format(qualifier, key, value, d._translate_timeperiod(key)))
fixture = {
QUALIFIER_YEARLY: {'2010000000': '2010000000',
'2011000000': '2011000000'}
}
for qualifier, f in fixture.items():
try:
_ = TimeperiodDict(qualifier, 5)
self.assertTrue(False, 'YEARLY should allow only identity grouping (i.e. grouping=1)')
except AssertionError:
self.assertTrue(True)
def test_hourly_translation(self):
test_dict = TimeperiodDict(QUALIFIER_HOURLY, 3)
fixture = OrderedDict()
fixture[(0, 4)] = '2010120303'
fixture[(4, 7)] = '2010120306'
fixture[(7, 10)] = '2010120309'
fixture[(10, 13)] = '2010120312'
fixture[(13, 16)] = '2010120315'
fixture[(16, 19)] = '2010120318'
fixture[(19, 22)] = '2010120321'
fixture[(22, 24)] = '2010120323'
timeperiod = '2010120300'
for boundaries, value in fixture.items():
lower_boundary, upper_boundary = boundaries
for i in range(lower_boundary, upper_boundary):
actual_value = test_dict._translate_timeperiod(timeperiod)
self.assertEqual(actual_value, value,
msg='failing combination: timeperiod={0} i={1} actual/expected={2}/{3}'.
format(timeperiod, i, actual_value, value))
timeperiod = time_helper.increment_timeperiod(QUALIFIER_HOURLY, timeperiod)
def test_daily_translation(self):
test_dict = TimeperiodDict(QUALIFIER_DAILY, 3)
fixture = OrderedDict()
fixture[(1, 4)] = '2010120300'
fixture[(4, 7)] = '2010120600'
fixture[(7, 10)] = '2010120900'
fixture[(10, 13)] = '2010121200'
fixture[(13, 16)] = '2010121500'
fixture[(16, 19)] = '2010121800'
fixture[(19, 22)] = '2010122100'
fixture[(22, 25)] = '2010122400'
fixture[(25, 28)] = '2010122700'
fixture[(28, 31)] = '2010123000'
fixture[(31, 32)] = '2010123100'
timeperiod = '2010120100'
for boundaries, value in fixture.items():
lower_boundary, upper_boundary = boundaries
for i in range(lower_boundary, upper_boundary):
actual_value = test_dict._translate_timeperiod(timeperiod)
self.assertEqual(actual_value, value,
msg='failing combination: timeperiod={0} i={1} actual/expected={2}/{3}'.
format(timeperiod, i, actual_value, value))
timeperiod = time_helper.increment_timeperiod(QUALIFIER_DAILY, timeperiod)
def test_container_methods(self):
test_dict = TimeperiodDict(QUALIFIER_HOURLY, 3)
timeperiod = '2010123100'
for i in range(0, 24):
# format {grouped_timeperiod: highest_loop_index}
test_dict[timeperiod] = i
timeperiod = time_helper.increment_timeperiod(QUALIFIER_HOURLY, timeperiod)
fixture = OrderedDict()
fixture[(0, 4)] = 3
fixture[(4, 7)] = 6
fixture[(7, 10)] = 9
fixture[(10, 13)] = 12
fixture[(13, 16)] = 15
fixture[(16, 19)] = 18
fixture[(19, 22)] = 21
fixture[(22, 24)] = 23
timeperiod = '2010123100'
for boundaries, value in fixture.items():
lower_boundary, upper_boundary = boundaries
for i in range(lower_boundary, upper_boundary):
self.assertEqual(test_dict[timeperiod], value,
msg='failing combination: timeperiod={0} i={1} actual/expected={2}/{3}'.
format(timeperiod, i, test_dict[timeperiod], value))
# get method
self.assertIsNotNone(test_dict.get(timeperiod), )
timeperiod = time_helper.increment_timeperiod(QUALIFIER_HOURLY, timeperiod)
# test __len__ method
self.assertEqual(len(test_dict), 8)
# test __iter__ method
counter = 0
for _ in test_dict:
counter += 1
self.assertEqual(counter, 8)
if __name__ == '__main__':
unittest.main()
| {
"repo_name": "mushkevych/scheduler",
"path": "tests/test_timeperiod_dict.py",
"copies": "1",
"size": "6819",
"license": "bsd-3-clause",
"hash": 3351614010348240400,
"line_mean": 42.4331210191,
"line_max": 105,
"alpha_frac": 0.5264701569,
"autogenerated": false,
"ratio": 4.1202416918429,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.51467118487429,
"avg_score": null,
"num_lines": null
} |
__author__ = 'Bohdan Mushkevych'
import unittest
from datetime import datetime, timedelta
from synergy.system.event_clock import EventClock, EventTime, parse_time_trigger_string, format_time_trigger_string
from synergy.system.repeat_timer import RepeatTimer
class TestEventClock(unittest.TestCase):
def test_utc_now(self):
utc_now = datetime.utcnow()
self.obj = EventTime.utc_now()
print(str(self.obj))
assert self.obj.day_of_week == str(utc_now.weekday()) \
and self.obj.time_of_day.hour == utc_now.hour \
and self.obj.time_of_day.minute == utc_now.minute \
and self.obj.time_of_day.second == 0 \
and self.obj.time_of_day.microsecond == 0
other_obj = EventTime.utc_now()
self.assertEqual(other_obj, self.obj)
def test_eq(self):
params = [EventTime(x) for x in ['17:00', '4-15:45', '*-09:00', '8:01']]
expected = [EventTime(x) for x in ['*-17:00', '2-17:00', '4-15:45', '*-09:00', '*-9:00', '*-08:01']]
not_expected = [EventTime(x) for x in ['*-17:15', '1-15:45', '*-9:01', '*-18:01']]
for event in expected:
self.assertIn(event, params)
for event in not_expected:
self.assertNotIn(event, params)
def test_parser(self):
fixture = {'every 300': (300, RepeatTimer),
'every 500': (500, RepeatTimer),
'every 1': (1, RepeatTimer),
'at *-17:00, 4-15:45,*-09:00 ': (['*-17:00', '4-15:45', '*-09:00'], EventClock),
'at 5-18:00 ,4-18:05 ,1-9:01 ': (['5-18:00', '4-18:05', '1-9:01'], EventClock),
'at *-08:01': (['*-08:01'], EventClock),
'at 8:30': (['8:30'], EventClock)}
for line, expected_output in fixture.items():
processed_tuple = parse_time_trigger_string(line)
self.assertEqual(processed_tuple, expected_output)
def test_formatter(self):
fixture = {RepeatTimer(300, None): 'every 300',
RepeatTimer(500, None): 'every 500',
RepeatTimer(1, None): 'every 1',
EventClock(['*-17:00', '4-15:45', '*-09:00'], None): 'at *-17:00,4-15:45,*-09:00',
EventClock(['5-18:00', '4-18:05', '1-9:01'], None): 'at 5-18:00,4-18:05,1-09:01',
EventClock(['*-08:01'], None): 'at *-08:01',
EventClock(['8:30'], None): 'at *-08:30'}
for handler, expected_output in fixture.items():
processed_tuple = format_time_trigger_string(handler)
self.assertEqual(processed_tuple, expected_output)
def test_next_run_in(self):
# 2014-05-01 is Thu. In Python it is weekday=3
fixed_utc_now = \
datetime(year=2014, month=05, day=01, hour=13, minute=00, second=00, microsecond=00, tzinfo=None)
fixture = {EventClock(['*-17:00', '4-15:45', '*-09:00'], None):
timedelta(days=0, hours=4, minutes=0, seconds=0, microseconds=0, milliseconds=0),
EventClock(['5-18:00', '4-18:05', '1-9:01'], None):
timedelta(days=1, hours=5, minutes=5, seconds=0, microseconds=0, milliseconds=0),
EventClock(['*-08:01'], None):
timedelta(days=0, hours=19, minutes=1, seconds=0, microseconds=0, milliseconds=0),
EventClock(['8:30'], None):
timedelta(days=0, hours=19, minutes=30, seconds=0, microseconds=0, milliseconds=0)}
for handler, expected_output in fixture.items():
handler.is_alive = lambda: True
processed_output = handler.next_run_in(utc_now=fixed_utc_now)
self.assertEqual(processed_output, expected_output)
if __name__ == '__main__':
unittest.main()
| {
"repo_name": "eggsandbeer/scheduler",
"path": "tests/test_event_clock.py",
"copies": "1",
"size": "3847",
"license": "bsd-3-clause",
"hash": -4417862393069892000,
"line_mean": 46.4938271605,
"line_max": 115,
"alpha_frac": 0.5489992202,
"autogenerated": false,
"ratio": 3.3249783923941227,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9365509854096049,
"avg_score": 0.0016935516996147385,
"num_lines": 81
} |
__author__ = 'Bohdan Mushkevych'
import unittest
from db.model.single_session import SingleSession
class TestSingleSession(unittest.TestCase):
def setUp(self):
self.obj = SingleSession()
def tearDown(self):
del self.obj
def test_key(self):
domain_name = 'test_name'
timeperiod = '20110101161633'
session_id = 'session_xxx_yyy'
self.obj.key = (domain_name, timeperiod, session_id)
temp = self.obj.key
assert temp[0] == domain_name
assert temp[1] == timeperiod
assert temp[2] == session_id
def test_session_id(self):
value = 'value_1234567890'
self.obj.session_id = value
assert self.obj.session_id == value
def test_os(self):
value = 'Windows MS PS 7.0.0.0.1.1.2'
self.obj.user_profile.os = value
assert self.obj.user_profile.os == value
def test_browser(self):
value = 'FF 3.4.5.6.7.8.9'
self.obj.user_profile.browser = value
assert self.obj.user_profile.browser == value
def test_ip(self):
value = '100.100.200.200'
self.obj.user_profile.ip = value
assert self.obj.user_profile.ip == value
def test_screen_res(self):
value_x = 1080
value_y = 980
self.obj.user_profile.screen_res = (value_x, value_y)
assert self.obj.user_profile.screen_x == value_x
assert self.obj.user_profile.screen_y == value_y
def test_language(self):
value = 'ca-uk'
self.obj.user_profile.language = value
assert self.obj.user_profile.language == value
def test_country(self):
value = 'ca'
self.obj.user_profile.country = value
assert self.obj.user_profile.country == value
def test_total_duration(self):
value = 123
self.obj.browsing_history.total_duration = value
assert self.obj.browsing_history.total_duration == value
def test_number_of_entries(self):
value = 12
self.obj.browsing_history.number_of_entries = value
assert self.obj.browsing_history.number_of_entries == value
if __name__ == '__main__':
unittest.main()
| {
"repo_name": "eggsandbeer/scheduler",
"path": "tests/test_single_session.py",
"copies": "1",
"size": "2176",
"license": "bsd-3-clause",
"hash": 3482754946242596000,
"line_mean": 28.8082191781,
"line_max": 67,
"alpha_frac": 0.6125919118,
"autogenerated": false,
"ratio": 3.476038338658147,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.45886302504581467,
"avg_score": null,
"num_lines": null
} |
__author__ = 'Bohdan Mushkevych'
import unittest
from settings import enable_test_mode
enable_test_mode()
from constants import PROCESS_SITE_DAILY
from db.model.raw_data import DOMAIN_NAME, TIMEPERIOD
from tests import hourly_fixtures, daily_fixtures
from tests.test_abstract_worker import AbstractWorkerUnitTest
from workers.site_daily_aggregator import SiteDailyAggregator
class SiteDailyAggregatorUnitTest(AbstractWorkerUnitTest):
def virtual_set_up(self):
super(SiteDailyAggregatorUnitTest, self).constructor(baseclass=SiteDailyAggregator,
process_name=PROCESS_SITE_DAILY,
output_prefix='EXPECTED_SITE_DAILY',
output_module=daily_fixtures,
generate_output=False,
compare_results=True)
hourly_fixtures.clean_site_entries()
return hourly_fixtures.generated_site_entries()
def virtual_tear_down(self):
hourly_fixtures.clean_site_entries()
def _get_key(self, obj):
return obj[DOMAIN_NAME], obj[TIMEPERIOD]
def test_aggregation(self):
super(SiteDailyAggregatorUnitTest, self).perform_aggregation()
if __name__ == '__main__':
unittest.main()
| {
"repo_name": "eggsandbeer/scheduler",
"path": "tests/test_site_daily_aggregator.py",
"copies": "1",
"size": "1423",
"license": "bsd-3-clause",
"hash": -6099458677106691000,
"line_mean": 37.4594594595,
"line_max": 97,
"alpha_frac": 0.5952213633,
"autogenerated": false,
"ratio": 4.635179153094462,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5730400516394463,
"avg_score": null,
"num_lines": null
} |
__author__ = 'Bohdan Mushkevych'
import unittest
from settings import enable_test_mode
enable_test_mode()
from db.model.raw_data import DOMAIN_NAME, TIMEPERIOD
from constants import PROCESS_SITE_YEARLY
from tests import monthly_fixtures
from tests import yearly_fixtures
from tests.test_abstract_worker import AbstractWorkerUnitTest
from workers.site_yearly_aggregator import SiteYearlyAggregator
class SiteYearlyAggregatorUnitTest(AbstractWorkerUnitTest):
def virtual_set_up(self):
super(SiteYearlyAggregatorUnitTest, self).constructor(baseclass=SiteYearlyAggregator,
process_name=PROCESS_SITE_YEARLY,
output_prefix='EXPECTED_SITE_YEARLY',
output_module=yearly_fixtures,
generate_output=False,
compare_results=True)
monthly_fixtures.clean_site_entries()
return monthly_fixtures.generated_site_entries()
def virtual_tear_down(self):
monthly_fixtures.clean_site_entries()
def _get_key(self, obj):
return obj[DOMAIN_NAME], obj[TIMEPERIOD]
def test_aggregation(self):
super(SiteYearlyAggregatorUnitTest, self).perform_aggregation()
if __name__ == '__main__':
unittest.main()
| {
"repo_name": "eggsandbeer/scheduler",
"path": "tests/test_site_yearly_aggregator.py",
"copies": "1",
"size": "1460",
"license": "bsd-3-clause",
"hash": -4187416878064004600,
"line_mean": 37.4210526316,
"line_max": 99,
"alpha_frac": 0.6006849315,
"autogenerated": false,
"ratio": 4.740259740259741,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.584094467175974,
"avg_score": null,
"num_lines": null
} |
__author__ = 'Bohdan Mushkevych'
import unittest
from settings import enable_test_mode
enable_test_mode()
from db.model.site_statistics import DOMAIN_NAME, TIMEPERIOD
from constants import PROCESS_SITE_HOURLY
from tests import hourly_fixtures
from tests.test_abstract_worker import AbstractWorkerUnitTest
from workers.site_hourly_aggregator import SiteHourlyAggregator
class SiteHourlyAggregatorUnitTest(AbstractWorkerUnitTest):
def virtual_set_up(self):
super(SiteHourlyAggregatorUnitTest, self).constructor(baseclass=SiteHourlyAggregator,
process_name=PROCESS_SITE_HOURLY,
output_prefix='EXPECTED_SITE_HOURLY',
output_module=hourly_fixtures,
generate_output=False,
compare_results=True)
hourly_fixtures.clean_session_entries()
return hourly_fixtures.generated_session_entries()
def virtual_tear_down(self):
hourly_fixtures.clean_session_entries()
def _get_key(self, obj):
return obj[DOMAIN_NAME], obj[TIMEPERIOD]
def test_aggregation(self):
super(SiteHourlyAggregatorUnitTest, self).perform_aggregation()
if __name__ == '__main__':
unittest.main()
| {
"repo_name": "mushkevych/scheduler",
"path": "tests/test_site_hourly_aggregator.py",
"copies": "1",
"size": "1437",
"license": "bsd-3-clause",
"hash": -199694802389473440,
"line_mean": 38.9166666667,
"line_max": 99,
"alpha_frac": 0.5984690327,
"autogenerated": false,
"ratio": 4.758278145695364,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5856747178395364,
"avg_score": null,
"num_lines": null
} |
__author__ = 'Bohdan Mushkevych'
import unittest
from odm import document, fields
class EmbeddedCollections(document.BaseDocument):
field_list = fields.ListField()
field_dict = fields.DictField()
field_id = fields.ObjectIdField(name='_id', null=True)
class TestDocument(unittest.TestCase):
def setUp(self):
self.maxDiff = None
self.model = EmbeddedCollections()
def tearDown(self):
del self.model
def test_getter_setter(self):
test_dict = dict()
for i in range(1, 100):
self.model.field_dict[i] = i * 100
test_dict[i] = i * 100
for i in range(1, 100):
self.model.field_list.append(i)
self.assertListEqual(self.model.field_list, list(range(1, 100)))
self.assertDictEqual(self.model.field_dict, test_dict)
def test_jsonification(self):
test_dict = dict()
for i in range(1, 100):
self.model.field_dict[i] = i * 100
test_dict[i] = i * 100
for i in range(1, 100):
self.model.field_list.append(i)
json_data = self.model.to_json()
self.assertIsInstance(json_data, dict)
m2 = EmbeddedCollections.from_json(json_data)
self.assertListEqual(m2.field_list, list(range(1, 100)))
self.assertDictEqual(m2.field_dict, test_dict)
def test_nullable_jsonification(self):
class FieldContainer(document.BaseDocument):
field_list = fields.ListField(null=True)
field_dict = fields.DictField(null=True)
model = FieldContainer()
json_data = model.to_json()
self.assertIsInstance(json_data, dict)
self.assertIsNone(model.field_list)
self.assertIsNone(model.field_dict)
m2 = FieldContainer.from_json(json_data)
self.assertIsNone(m2.field_list)
self.assertIsNone(m2.field_dict)
if __name__ == '__main__':
unittest.main()
| {
"repo_name": "mushkevych/synergy_odm",
"path": "tests/test_collection_fields.py",
"copies": "1",
"size": "1944",
"license": "bsd-3-clause",
"hash": 4793093026999238000,
"line_mean": 28.0149253731,
"line_max": 72,
"alpha_frac": 0.6193415638,
"autogenerated": false,
"ratio": 3.5801104972375692,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4699452061037569,
"avg_score": null,
"num_lines": null
} |
__author__ = 'Bohdan Mushkevych'
import unittest
from synergy.conf import settings
from flow.core.ephemeral_cluster import EphemeralCluster
from flow.core.execution_context import ExecutionContext
from flow.core.step_executor import StepExecutor, ACTIONSET_COMPLETE, ACTIONSET_FAILED, ACTIONSET_PENDING
from flow.core.simple_actions import FailureAction, IdentityAction
TEST_PRESET_TIMEPERIOD = '2016060107'
TEST_START_TIMEPERIOD = '2016060107'
TEST_END_TIMEPERIOD = '2016060108'
class StepExecutorTest(unittest.TestCase):
def setUp(self):
flow_name = 'ut_flow_name'
self.context = ExecutionContext(flow_name, TEST_PRESET_TIMEPERIOD, TEST_START_TIMEPERIOD, TEST_END_TIMEPERIOD,
settings.settings)
self.ephemeral_cluster = EphemeralCluster('unit test cluster', self.context)
def tearDown(self):
pass
def test_simple_step(self):
""" method tests happy-flow for the execution flow """
sa_identity = IdentityAction()
step_exec = StepExecutor(step_name='a step',
main_action=sa_identity,
pre_actions=[sa_identity],
post_actions=[sa_identity])
step_exec.set_context(self.context)
self.assertFalse(step_exec.is_complete)
self.assertEqual(step_exec.pre_actionset.state, ACTIONSET_PENDING)
self.assertEqual(step_exec.main_actionset.state, ACTIONSET_PENDING)
self.assertEqual(step_exec.post_actionset.state, ACTIONSET_PENDING)
step_exec.do(self.ephemeral_cluster)
self.assertTrue(step_exec.is_complete)
self.assertEqual(step_exec.pre_actionset.state, ACTIONSET_COMPLETE)
self.assertEqual(step_exec.main_actionset.state, ACTIONSET_COMPLETE)
self.assertEqual(step_exec.post_actionset.state, ACTIONSET_COMPLETE)
def test_failing_step(self):
""" method tests execution step, where one of the phases is failing """
sa_identity = IdentityAction()
sa_failure = FailureAction()
step_exec = StepExecutor(step_name='a step',
main_action=sa_failure,
pre_actions=[sa_identity],
post_actions=[sa_identity])
step_exec.set_context(self.context)
self.assertFalse(step_exec.is_complete)
step_exec.do(self.ephemeral_cluster)
self.assertFalse(step_exec.is_complete)
self.assertEqual(step_exec.pre_actionset.state, ACTIONSET_COMPLETE)
self.assertEqual(step_exec.main_actionset.state, ACTIONSET_FAILED)
self.assertEqual(step_exec.post_actionset.state, ACTIONSET_PENDING)
if __name__ == '__main__':
unittest.main()
| {
"repo_name": "mushkevych/synergy_flow",
"path": "tests/test_step_executor.py",
"copies": "1",
"size": "2778",
"license": "bsd-3-clause",
"hash": 4109005751178824700,
"line_mean": 41.7384615385,
"line_max": 118,
"alpha_frac": 0.658387329,
"autogenerated": false,
"ratio": 3.918194640338505,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0004554158383237184,
"num_lines": 65
} |
__author__ = 'Bohdan Mushkevych'
import unittest
from synergy.system.time_qualifier import *
from context import PROCESS_SITE_HOURLY, PROCESS_SITE_DAILY, PROCESS_SITE_MONTHLY, PROCESS_SITE_YEARLY, \
PROCESS_BASH_DRIVER
from synergy.scheduler.process_hierarchy import ProcessHierarchy
class TestProcessHierarchy(unittest.TestCase):
def _perform_assertions(self, hierarchy, process_name_desc, time_qualifier_desc,
top_process_name, bottom_process_name):
index = 0
for hierarchy_key in hierarchy:
process_name = process_name_desc[index]
index += 1
self.assertEqual(hierarchy[hierarchy_key].process_entry.process_name, process_name)
self.assertEqual(hierarchy.top_process.process_name, top_process_name)
self.assertEqual(hierarchy.bottom_process.process_name, bottom_process_name)
for process_name in process_name_desc:
self.assertIn(process_name, hierarchy)
for qualifier in time_qualifier_desc:
self.assertTrue(hierarchy.has_qualifier(qualifier))
def test_four_level(self):
hierarchy = ProcessHierarchy(PROCESS_SITE_HOURLY, PROCESS_SITE_YEARLY, PROCESS_SITE_MONTHLY, PROCESS_SITE_DAILY)
process_name_desc = [PROCESS_SITE_YEARLY, PROCESS_SITE_MONTHLY, PROCESS_SITE_DAILY, PROCESS_SITE_HOURLY]
time_qualifier_desc = [QUALIFIER_YEARLY, QUALIFIER_MONTHLY, QUALIFIER_DAILY, QUALIFIER_HOURLY]
self._perform_assertions(hierarchy, process_name_desc, time_qualifier_desc,
PROCESS_SITE_YEARLY, PROCESS_SITE_HOURLY)
def test_three_level(self):
hierarchy = ProcessHierarchy(PROCESS_SITE_HOURLY, PROCESS_SITE_MONTHLY, PROCESS_SITE_DAILY)
process_name_desc = [PROCESS_SITE_MONTHLY, PROCESS_SITE_DAILY, PROCESS_SITE_HOURLY]
time_qualifier_desc = [QUALIFIER_MONTHLY, QUALIFIER_DAILY, QUALIFIER_HOURLY]
self._perform_assertions(hierarchy, process_name_desc, time_qualifier_desc,
PROCESS_SITE_MONTHLY, PROCESS_SITE_HOURLY)
def test_two_level(self):
hierarchy = ProcessHierarchy(PROCESS_SITE_HOURLY, PROCESS_SITE_DAILY)
process_name_desc = [PROCESS_SITE_DAILY, PROCESS_SITE_HOURLY]
time_qualifier_desc = [QUALIFIER_DAILY, QUALIFIER_HOURLY]
self._perform_assertions(hierarchy, process_name_desc, time_qualifier_desc,
PROCESS_SITE_DAILY, PROCESS_SITE_HOURLY)
def test_one_level(self):
hierarchy = ProcessHierarchy(PROCESS_SITE_DAILY)
process_name_desc = [PROCESS_SITE_DAILY]
time_qualifier_desc = [QUALIFIER_DAILY]
self._perform_assertions(hierarchy, process_name_desc, time_qualifier_desc,
PROCESS_SITE_DAILY, PROCESS_SITE_DAILY)
def test_mix(self):
hierarchy = ProcessHierarchy(PROCESS_SITE_HOURLY, PROCESS_SITE_YEARLY)
process_name_desc = [PROCESS_SITE_YEARLY, PROCESS_SITE_HOURLY]
time_qualifier_desc = [QUALIFIER_YEARLY, QUALIFIER_HOURLY]
self._perform_assertions(hierarchy, process_name_desc, time_qualifier_desc,
PROCESS_SITE_YEARLY, PROCESS_SITE_HOURLY)
def test_invalid_process_name(self):
try:
ProcessHierarchy(PROCESS_BASH_DRIVER, PROCESS_SITE_HOURLY)
self.assertTrue(False, 'AttributeError should have been thrown for improper hierarchical process')
except AttributeError:
self.assertTrue(True, 'AttributeError was expected and caught')
if __name__ == '__main__':
unittest.main()
| {
"repo_name": "eggsandbeer/scheduler",
"path": "tests/test_process_hierarchy.py",
"copies": "1",
"size": "3643",
"license": "bsd-3-clause",
"hash": -4439504434706716700,
"line_mean": 42.8915662651,
"line_max": 120,
"alpha_frac": 0.6771891298,
"autogenerated": false,
"ratio": 3.5541463414634147,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9721011984002921,
"avg_score": 0.0020646974520988574,
"num_lines": 83
} |
__author__ = 'Bohdan Mushkevych'
import unittest
try:
import mock
except ImportError:
from unittest import mock
from settings import enable_test_mode
enable_test_mode()
from constants import PROCESS_SITE_HOURLY
from synergy.db.dao.job_dao import JobDao
from synergy.db.dao.unit_of_work_dao import UnitOfWorkDao
from synergy.db.model import job, unit_of_work
from synergy.db.manager.ds_manager import BaseManager
from synergy.system.system_logger import get_logger
from synergy.scheduler.timetable import Timetable
from synergy.scheduler.state_machine_continuous import StateMachineContinuous
from tests.state_machine_testing_utils import *
from tests.base_fixtures import create_unit_of_work
from tests.ut_context import PROCESS_UNIT_TEST
class ContinuousSMUnitTest(unittest.TestCase):
def setUp(self):
self.logger = get_logger(PROCESS_UNIT_TEST)
self.time_table_mocked = mock.create_autospec(Timetable)
self.job_dao_mocked = mock.create_autospec(JobDao)
self.uow_dao_mocked = mock.create_autospec(UnitOfWorkDao)
self.ds_mocked = mock.create_autospec(BaseManager)
self.sm_real = StateMachineContinuous(self.logger, self.time_table_mocked)
self.sm_real.uow_dao = self.uow_dao_mocked
self.sm_real.job_dao = self.job_dao_mocked
self.sm_real.ds = self.ds_mocked
self.sm_real.update_job = mock.Mock(side_effect=self.sm_real.update_job)
self.sm_real._process_state_final_run = mock.Mock(side_effect=self.sm_real._process_state_final_run)
self.sm_real._process_state_in_progress = mock.Mock(side_effect=self.sm_real._process_state_in_progress)
def tearDown(self):
pass
def test_compute_next_job_state(self):
""" method validated logic behind selection of the next Job state """
self.sm_real.insert_and_publish_uow = then_return_uow
# use-case 1: make sure it is STATE_IN_PROGRESS for current timeperiod and non-finalizable job
job_record = get_job_record(job.STATE_EMBRYO, TEST_ACTUAL_TIMEPERIOD, PROCESS_SITE_HOURLY)
self.time_table_mocked.is_job_record_finalizable = mock.MagicMock(return_value=False)
self.assertEqual(self.sm_real._compute_next_job_state(job_record), job.STATE_IN_PROGRESS)
# use-case 2: make sure it is STATE_IN_PROGRESS for past timeperiod and non-finalizable job
job_record = get_job_record(job.STATE_EMBRYO, TEST_PAST_TIMEPERIOD, PROCESS_SITE_HOURLY)
self.time_table_mocked.is_job_record_finalizable = mock.MagicMock(return_value=False)
self.assertEqual(self.sm_real._compute_next_job_state(job_record), job.STATE_IN_PROGRESS)
# use-case 3: make sure it is STATE_IN_PROGRESS for current timeperiod and finalizable job
job_record = get_job_record(job.STATE_EMBRYO, TEST_ACTUAL_TIMEPERIOD, PROCESS_SITE_HOURLY)
self.time_table_mocked.is_job_record_finalizable = mock.MagicMock(return_value=True)
self.assertEqual(self.sm_real._compute_next_job_state(job_record), job.STATE_IN_PROGRESS)
# use-case 4: make sure it is STATE_FINAL_RUN for past timeperiod and finalizable job
job_record = get_job_record(job.STATE_EMBRYO, TEST_PAST_TIMEPERIOD, PROCESS_SITE_HOURLY)
self.time_table_mocked.is_job_record_finalizable = mock.MagicMock(return_value=True)
self.assertEqual(self.sm_real._compute_next_job_state(job_record), job.STATE_FINAL_RUN)
# use-case 5: make sure the exception is thrown for future timeperiod
job_record = get_job_record(job.STATE_EMBRYO, TEST_FUTURE_TIMEPERIOD, PROCESS_SITE_HOURLY)
self.time_table_mocked.is_job_record_finalizable = mock.MagicMock(return_value=True)
try:
self.sm_real._compute_next_job_state(job_record)
self.assertTrue(False, 'an exception is expected to be thrown')
except ValueError:
self.assertTrue(True, 'an exception is expected')
def test_state_embryo(self):
""" method tests job records in STATE_EMBRYO state"""
self.sm_real.insert_and_publish_uow = then_return_uow
self.sm_real._compute_next_job_state = mock.MagicMock(return_value=job.STATE_IN_PROGRESS)
job_record = get_job_record(job.STATE_EMBRYO, TEST_PRESET_TIMEPERIOD, PROCESS_SITE_HOURLY)
self.sm_real.manage_job(job_record)
self.sm_real.update_job.assert_called_once_with(mock.ANY, mock.ANY, mock.ANY)
def test_duplicatekeyerror_state_embryo(self):
""" method tests job records in STATE_EMBRYO state"""
self.sm_real._insert_uow = then_raise_uw
job_record = get_job_record(job.STATE_EMBRYO, TEST_PRESET_TIMEPERIOD, PROCESS_SITE_HOURLY)
try:
self.sm_real.manage_job(job_record)
self.assertTrue(False, 'UserWarning exception should have been thrown')
except UserWarning:
self.assertTrue(True)
def test_future_timeperiod_state_in_progress(self):
""" method tests timetable records in STATE_IN_PROGRESS state"""
job_record = get_job_record(job.STATE_IN_PROGRESS, TEST_FUTURE_TIMEPERIOD, PROCESS_SITE_HOURLY)
manual_uow = create_unit_of_work(PROCESS_SITE_HOURLY, 0, 1, TEST_ACTUAL_TIMEPERIOD)
self.uow_dao_mocked.get_one = mock.MagicMock(return_value=manual_uow)
self.time_table_mocked.is_job_record_finalizable = mock.MagicMock(return_value=True)
self.sm_real.insert_and_publish_uow = then_raise_uw
self.sm_real.manage_job(job_record)
self.assertEqual(len(self.sm_real.update_job.call_args_list), 0)
def test_preset_timeperiod_state_in_progress(self):
""" method tests timetable records in STATE_IN_PROGRESS state"""
self.time_table_mocked.is_job_record_finalizable = mock.MagicMock(return_value=True)
self.uow_dao_mocked.get_one = mock.MagicMock(
side_effect=lambda *_: create_unit_of_work(PROCESS_SITE_HOURLY, 0, 1, TEST_ACTUAL_TIMEPERIOD))
self.sm_real.insert_and_publish_uow = then_return_uow
job_record = get_job_record(job.STATE_IN_PROGRESS, TEST_PRESET_TIMEPERIOD, PROCESS_SITE_HOURLY)
self.sm_real.manage_job(job_record)
self.assertEqual(len(self.sm_real.update_job.call_args_list), 0)
self.assertEqual(len(self.sm_real._process_state_final_run.call_args_list), 0)
def test_transfer_to_final_state_from_in_progress(self):
""" method tests timetable records in STATE_IN_PROGRESS state"""
self.time_table_mocked.is_job_record_finalizable = mock.MagicMock(return_value=True)
self.uow_dao_mocked.get_one = mock.MagicMock(
side_effect=lambda *_: create_unit_of_work(
PROCESS_SITE_HOURLY, 1, 1, TEST_ACTUAL_TIMEPERIOD, unit_of_work.STATE_PROCESSED))
self.sm_real.insert_and_publish_uow = then_return_duplicate_uow
job_record = get_job_record(job.STATE_IN_PROGRESS, TEST_PRESET_TIMEPERIOD, PROCESS_SITE_HOURLY)
self.sm_real.manage_job(job_record)
self.assertEqual(len(self.sm_real.update_job.call_args_list), 1)
self.assertEqual(len(self.sm_real._process_state_in_progress.call_args_list), 1)
self.assertEqual(len(self.sm_real._process_state_final_run.call_args_list), 0)
def test_retry_state_in_progress(self):
""" method tests timetable records in STATE_IN_PROGRESS state"""
self.time_table_mocked.is_job_record_finalizable = mock.MagicMock(return_value=True)
self.uow_dao_mocked.get_one = mock.MagicMock(
side_effect=lambda *_: create_unit_of_work(
PROCESS_SITE_HOURLY, 1, 1, TEST_ACTUAL_TIMEPERIOD, unit_of_work.STATE_PROCESSED))
self.sm_real.insert_and_publish_uow = then_return_uow
job_record = get_job_record(job.STATE_IN_PROGRESS, TEST_PRESET_TIMEPERIOD, PROCESS_SITE_HOURLY)
self.sm_real.manage_job(job_record)
self.assertEqual(len(self.sm_real.update_job.call_args_list), 1)
self.assertEqual(len(self.sm_real._process_state_in_progress.call_args_list), 1)
self.assertEqual(len(self.sm_real._process_state_final_run.call_args_list), 0)
def test_processed_state_final_run(self):
"""method tests timetable records in STATE_FINAL_RUN state"""
self.uow_dao_mocked.get_one = mock.MagicMock(
side_effect=lambda *_: create_unit_of_work(
PROCESS_SITE_HOURLY, 1, 1, TEST_ACTUAL_TIMEPERIOD, unit_of_work.STATE_PROCESSED))
job_record = get_job_record(job.STATE_FINAL_RUN, TEST_PRESET_TIMEPERIOD, PROCESS_SITE_HOURLY)
self.sm_real.manage_job(job_record)
self.assertEqual(len(self.sm_real.update_job.call_args_list), 1)
self.assertEqual(len(self.time_table_mocked.get_tree.call_args_list), 1)
def test_cancelled_state_final_run(self):
"""method tests timetable records in STATE_FINAL_RUN state"""
self.uow_dao_mocked.get_one = mock.MagicMock(
side_effect=lambda *_: create_unit_of_work(
PROCESS_SITE_HOURLY, 1, 1, TEST_ACTUAL_TIMEPERIOD, unit_of_work.STATE_CANCELED))
job_record = get_job_record(job.STATE_FINAL_RUN, TEST_PRESET_TIMEPERIOD, PROCESS_SITE_HOURLY)
self.sm_real.manage_job(job_record)
self.assertEqual(len(self.sm_real.update_job.call_args_list), 1)
self.assertEqual(len(self.time_table_mocked.get_tree.call_args_list), 1)
def test_state_skipped(self):
"""method tests timetable records in STATE_SKIPPED state"""
job_record = get_job_record(job.STATE_SKIPPED, TEST_PRESET_TIMEPERIOD, PROCESS_SITE_HOURLY)
self.sm_real.manage_job(job_record)
self.assertEqual(len(self.sm_real.update_job.call_args_list), 0)
self.assertEqual(len(self.time_table_mocked.get_tree.call_args_list), 0)
def test_state_processed(self):
"""method tests timetable records in STATE_PROCESSED state"""
job_record = get_job_record(job.STATE_PROCESSED, TEST_PRESET_TIMEPERIOD, PROCESS_SITE_HOURLY)
self.sm_real.manage_job(job_record)
self.assertEqual(len(self.sm_real.update_job.call_args_list), 0)
self.assertEqual(len(self.time_table_mocked.get_tree.call_args_list), 0)
if __name__ == '__main__':
unittest.main()
| {
"repo_name": "mushkevych/scheduler",
"path": "tests/test_state_machine_continuous.py",
"copies": "1",
"size": "10232",
"license": "bsd-3-clause",
"hash": -385314419994460350,
"line_mean": 50.16,
"line_max": 112,
"alpha_frac": 0.6968334636,
"autogenerated": false,
"ratio": 3.227760252365931,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9404876326924323,
"avg_score": 0.003943477808321677,
"num_lines": 200
} |
__author__ = 'Bohdan Mushkevych'
import unittest
try:
import mock
except ImportError:
from unittest import mock
from settings import enable_test_mode
enable_test_mode()
from synergy.db.dao.unit_of_work_dao import UnitOfWorkDao
from synergy.db.dao.log_recording_dao import LogRecordingDao
from synergy.system.system_logger import get_logger
from synergy.system.mq_transmitter import MqTransmitter
from synergy.workers.abstract_uow_aware_worker import AbstractUowAwareWorker
from tests.base_fixtures import create_and_insert_unit_of_work, TestMessage
from context import PROCESS_ALERT_DAILY
INFO_LOG_MESSAGES = [f'111222333 INFO log message string {x}' for x in range(10)]
WARN_LOG_MESSAGES = [f'444555666 WARNING log message string {x}' for x in range(10)]
STD_MESSAGES = [f'777888999 STD OUTPUT message {x}' for x in range(10)]
class TheWorker(AbstractUowAwareWorker):
def __init__(self, process_name):
super(TheWorker, self).__init__(process_name, perform_db_logging=True)
self.mq_transmitter = mock.create_autospec(MqTransmitter)
def _init_performance_tracker(self, logger):
super(TheWorker, self)._init_performance_tracker(logger)
self.performance_tracker.cancel()
def _init_mq_consumer(self):
self.consumer = mock.Mock()
class ChattyWorker(TheWorker):
def _process_uow(self, uow):
for message in INFO_LOG_MESSAGES:
self.logger.info(message)
for message in WARN_LOG_MESSAGES:
self.logger.warning(message)
for message in STD_MESSAGES:
print(message)
class ExceptionWorker(TheWorker):
def _process_uow(self, uow):
try:
raise ValueError('Artificially triggered exception to test Uow Exception Logging')
except Exception as e:
self.logger.error(f'Exception: {e}', exc_info=True)
class LogRecordingHandlerUnitTest(unittest.TestCase):
""" Test flow:
1. create a UOW in the database
2. emulate mq message
3. call _mq_callback method
4. validate that all the messages are now found in the uow_log record
5. remove UOW and uow_log record
"""
def setUp(self):
self.process_name = PROCESS_ALERT_DAILY
self.logger = get_logger(self.process_name)
self.uow_id = create_and_insert_unit_of_work(self.process_name, 'range_start', 'range_end')
self.uow_id = str(self.uow_id)
self.uow_dao = UnitOfWorkDao(self.logger)
self.log_recording_dao = LogRecordingDao(self.logger)
def tearDown(self):
self.uow_dao.remove(self.uow_id)
self.log_recording_dao.remove(self.uow_id)
def test_logging(self):
self.worker = ChattyWorker(self.process_name)
message = TestMessage(process_name=self.process_name, uow_id=self.uow_id)
self.worker._mq_callback(message)
uow_log = self.log_recording_dao.get_one(self.uow_id)
messages = INFO_LOG_MESSAGES + WARN_LOG_MESSAGES # + STD_MESSAGES
self.assertLessEqual(len(messages), len(uow_log.log))
for index, message in enumerate(messages):
self.assertIn(message, uow_log.log[index])
def test_exception_logging(self):
self.worker = ExceptionWorker(self.process_name)
message = TestMessage(process_name=self.process_name, uow_id=self.uow_id)
self.worker._mq_callback(message)
uow_log = self.log_recording_dao.get_one(self.uow_id)
messages = ['Exception: Artificially triggered exception to test Uow Exception Logging',
'Method ExceptionWorker._process_uow returned None. Assuming happy flow.',
'at INVALID_TIMEPERIOD: Success/Failure 0/0 entries']
for index, message in enumerate(messages):
self.assertIn(message, uow_log.log[index])
if __name__ == '__main__':
unittest.main()
| {
"repo_name": "mushkevych/scheduler",
"path": "tests/test_log_recording_handler.py",
"copies": "1",
"size": "3875",
"license": "bsd-3-clause",
"hash": 113173441170446620,
"line_mean": 36.2596153846,
"line_max": 99,
"alpha_frac": 0.6807741935,
"autogenerated": false,
"ratio": 3.558310376492195,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47390845699921946,
"avg_score": null,
"num_lines": null
} |
__author__ = 'Bohdan Mushkevych'
import unittest
try:
import mock
except ImportError:
from unittest import mock
from tests import ut_flows
ut_flows.register_flows()
from synergy.conf import settings
from flow.conf import flows
from flow.core.flow_graph_node import FlowGraphNode
from flow.core.execution_context import ExecutionContext
from flow.core.step_executor import StepExecutor, ACTIONSET_COMPLETE
from flow.core.ephemeral_cluster import EphemeralCluster
TEST_PRESET_TIMEPERIOD = '2016060107'
TEST_START_TIMEPERIOD = '2016060107'
TEST_END_TIMEPERIOD = '2016060108'
class FlowGraphTest(unittest.TestCase):
def setUp(self):
flow_name = 'ut_flow_name'
self.context = ExecutionContext(flow_name, TEST_PRESET_TIMEPERIOD, TEST_START_TIMEPERIOD, TEST_END_TIMEPERIOD,
settings.settings)
def tearDown(self):
pass
@mock.patch('flow.core.flow_graph.FlowDao')
def test_set_context(self, mock_flow_dao):
"""
flow_dao is mocked to prevent performing
read/write operations on the DB
as this UT is about testing the iterator logic
"""
the_flow = flows.flows[ut_flows.UNIT_TEST_FLOW_SIMPLE]
self.assertIsNone(the_flow.context)
the_flow.set_context(self.context)
self.assertIsNotNone(the_flow.context)
@mock.patch('flow.core.flow_graph.FlowDao')
@mock.patch('flow.core.flow_graph.StepDao')
@mock.patch('flow.core.flow_graph_node.StepDao')
@mock.patch('flow.core.flow_graph.LogRecordingHandler')
@mock.patch('flow.core.flow_graph_node.LogRecordingHandler')
def test_simple_iterator(self, flow_flow_dao, flow_step_dao, step_step_dao,
flow_recording_handler, step_recording_handler):
""" method tests happy-flow for the iterator """
the_flow = flows.flows[ut_flows.UNIT_TEST_FLOW_SIMPLE]
the_flow.set_context(self.context)
the_flow.mark_start()
steps_order = list()
for step_name in the_flow:
steps_order.append(step_name)
step = the_flow[step_name]
assert isinstance(step, FlowGraphNode)
step.set_context(self.context)
step.mark_start()
assert isinstance(step.step_executor, StepExecutor)
step.step_executor.pre_actionset.state = ACTIONSET_COMPLETE
step.step_executor.main_actionset.state = ACTIONSET_COMPLETE
step.step_executor.post_actionset.state = ACTIONSET_COMPLETE
step.mark_success()
self.assertListEqual(steps_order, ['step_1', 'step_2', 'step_3', 'step_4',
'step_5', 'step_6', 'step_7', 'step_8'])
@mock.patch('flow.core.flow_graph.FlowDao')
@mock.patch('flow.core.flow_graph.StepDao')
@mock.patch('flow.core.flow_graph_node.StepDao')
@mock.patch('flow.core.flow_graph.LogRecordingHandler')
@mock.patch('flow.core.flow_graph_node.LogRecordingHandler')
def test_interrupted_iterator(self, flow_flow_dao, flow_step_dao, step_step_dao,
flow_recording_handler, step_recording_handler):
""" method tests iterator interrupted by failed step """
the_flow = flows.flows[ut_flows.UNIT_TEST_FLOW_FAILURE]
the_flow.set_context(self.context)
the_flow.mark_start()
ephemeral_cluster = EphemeralCluster('unit test cluster', self.context)
steps_order = list()
for step_name in the_flow:
steps_order.append(step_name)
step = the_flow[step_name]
assert isinstance(step, FlowGraphNode)
step.set_context(self.context)
step.run(ephemeral_cluster)
self.assertListEqual(steps_order, ['step_1', 'step_2', 'step_3', 'step_4'])
def test_all_dependant_steps(self):
""" method verifies if iterator interrupted by failed step """
the_flow = flows.flows[ut_flows.UNIT_TEST_FLOW_SIMPLE]
self.assertSetEqual(set(the_flow.all_dependant_steps('step_1')),
{'step_2', 'step_3', 'step_4', 'step_5', 'step_6', 'step_7', 'step_8'})
self.assertSetEqual(set(the_flow.all_dependant_steps('step_2')),
{'step_3', 'step_4', 'step_5', 'step_6', 'step_7', 'step_8'})
self.assertSetEqual(set(the_flow.all_dependant_steps('step_3')), {'step_5'})
self.assertSetEqual(set(the_flow.all_dependant_steps('step_6')), {'step_7', 'step_8'})
if __name__ == '__main__':
unittest.main()
| {
"repo_name": "mushkevych/synergy_flow",
"path": "tests/test_flow_graph.py",
"copies": "1",
"size": "4570",
"license": "bsd-3-clause",
"hash": -3215478460911542000,
"line_mean": 40.1711711712,
"line_max": 118,
"alpha_frac": 0.6374179431,
"autogenerated": false,
"ratio": 3.5703125,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.969667578535523,
"avg_score": 0.002210931548953984,
"num_lines": 111
} |
__author__ = 'Bohdan Mushkevych'
try:
from http.client import NO_CONTENT
except ImportError:
from httplib import NO_CONTENT
import json
from werkzeug.wrappers import Response
from synergy.mx.utils import render_template, expose
from flow.mx.flow_action_handler import FlowActionHandler, RUN_MODE_RUN_ONE, RUN_MODE_RUN_FROM
# for future use
@expose('/flow/step/details/')
def details_flow_step(request, **values):
details = FlowActionHandler(request, **values)
return Response(response=json.dumps(details.step_details), mimetype='application/json')
# for future use
@expose('/flow/flow/details/')
def details_flow(request, **values):
details = FlowActionHandler(request, **values)
return Response(response=json.dumps(details.flow_details), mimetype='application/json')
@expose('/flow/run/mode/')
def set_run_mode(request, **values):
handler = FlowActionHandler(request, **values)
handler.set_run_mode()
return Response(status=NO_CONTENT)
@expose('/flow/run/one_step/')
def run_one_step(request, **values):
handler = FlowActionHandler(request, **values)
return Response(response=json.dumps(handler.perform_freerun_action(RUN_MODE_RUN_ONE)),
mimetype='application/json')
@expose('/flow/run/from_step/')
def run_from_step(request, **values):
handler = FlowActionHandler(request, **values)
return Response(response=json.dumps(handler.perform_freerun_action(RUN_MODE_RUN_FROM)),
mimetype='application/json')
@expose('/flow/step/log/')
def get_step_log(request, **values):
handler = FlowActionHandler(request, **values)
return Response(response=json.dumps(handler.get_step_log()), mimetype='application/json')
@expose('/flow/flow/log/')
def get_flow_log(request, **values):
handler = FlowActionHandler(request, **values)
return Response(response=json.dumps(handler.get_flow_log()), mimetype='application/json')
@expose('/flow/viewer/')
def flow_viewer(request, **values):
handler = FlowActionHandler(request, **values)
return render_template('flow_viewer.html',
flow_details=handler.flow_details,
process_name=handler.process_name,
active_run_mode=handler.active_run_mode,
freerun_uows=handler.freerun_uow_records)
| {
"repo_name": "mushkevych/synergy_flow",
"path": "flow/mx/views.py",
"copies": "1",
"size": "2351",
"license": "bsd-3-clause",
"hash": 6102536044288337000,
"line_mean": 33.0724637681,
"line_max": 94,
"alpha_frac": 0.6924712888,
"autogenerated": false,
"ratio": 3.6677067082683306,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9854714184157074,
"avg_score": 0.0010927625822512962,
"num_lines": 69
} |
__author__ = 'Bohdan Mushkevych'
try:
import mock
except ImportError:
from unittest import mock
from settings import enable_test_mode
enable_test_mode()
import types
import unittest
import process_starter
from six import class_types, PY2, PY3
def main_function(*args):
return args
class OldClass:
def starter_method(self, *args):
return args
class NewClass(object):
def starter_method(self, *args):
return args
class TestProcessStarter(unittest.TestCase):
def test_type_old_class(self):
t, m, starter = process_starter.get_class('tests.test_process_starter.OldClass')
self.assertIn(t, class_types)
self.assertIsInstance(m, class_types)
self.assertIsNone(starter)
def test_type_new_class(self):
t, m, starter = process_starter.get_class('tests.test_process_starter.NewClass')
self.assertIn(t, class_types)
self.assertIsInstance(m, class_types)
self.assertIsNone(starter)
def test_type_function(self):
t, m, starter = process_starter.get_class('tests.test_process_starter.main_function')
self.assertEqual(t, types.FunctionType)
self.assertIsInstance(m, types.FunctionType)
self.assertIsNone(starter)
def test_old_class_method(self):
t, m, starter = process_starter.get_class('tests.test_process_starter.OldClass.starter_method')
self.assertIn(t, class_types)
self.assertIsInstance(m, class_types)
self.assertEqual(starter, 'starter_method')
def test_not_class(self):
t, m, starter = process_starter.get_class('tests.test_process_starter.main_function')
self.assertEqual(t, types.FunctionType)
self.assertIsInstance(m, types.FunctionType)
self.assertNotIsInstance(m, class_types)
self.assertIsNone(starter)
def test_starter_method(self):
t, m, starter = process_starter.get_class('tests.test_process_starter.NewClass.starter_method')
self.assertIn(t, class_types)
self.assertIsInstance(m, class_types)
self.assertEqual(starter, 'starter_method')
self.assertIsInstance(getattr(m(), starter), types.MethodType)
if PY2:
self.assertIsInstance(getattr(m, starter), types.MethodType)
if PY3:
self.assertIsInstance(getattr(m, starter), types.FunctionType)
def test_python_types(self):
class _C(object):
def m(self):
pass
self.assertEqual(type(_C), type)
self.assertIsInstance(getattr(_C(), 'm'), types.MethodType)
self.assertEqual(type(_C().m), types.MethodType)
if PY2:
self.assertIsInstance(getattr(_C, 'm'), types.MethodType)
self.assertEqual(type(_C.m), types.MethodType)
if PY3:
self.assertIsInstance(getattr(_C, 'm'), types.FunctionType)
self.assertEqual(type(_C.m), types.FunctionType)
@mock.patch('workers.abstract_worker.SimpleTracker')
def test_starting_method(self, mock_tracker):
"""
performance_tracker must be mocked
otherwise they will instantiate threads
and prevent Unit Tests from finishing
"""
from tests.ut_process_context import PROCESS_CLASS_EXAMPLE
process_starter.start_by_process_name(PROCESS_CLASS_EXAMPLE, None)
def test_starting_function(self):
from tests.ut_process_context import PROCESS_SCRIPT_EXAMPLE
process_starter.start_by_process_name(PROCESS_SCRIPT_EXAMPLE, 'parameters')
if __name__ == '__main__':
unittest.main()
| {
"repo_name": "mushkevych/launch.py",
"path": "tests/test_process_starter.py",
"copies": "1",
"size": "3591",
"license": "bsd-3-clause",
"hash": -8991277941250797000,
"line_mean": 32.25,
"line_max": 103,
"alpha_frac": 0.6649958229,
"autogenerated": false,
"ratio": 3.756276150627615,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9908119141848962,
"avg_score": 0.002630566335730536,
"num_lines": 108
} |
__author__ = 'Bohdan'
import time
class AminisLastErrorHolder:
def __init__(self):
self.errorText = ""
self.__hasError = False
def clearError(self):
self.errorText = ""
self.__hasError = False
def setError(self, errorText):
self.errorText = errorText
self.__hasError = True
@property
def hasError(self):
return self.__hasError
def timeDelta(timeBegin):
end = time.time()
secs = end - timeBegin
msecs = (end - timeBegin) * 1000.0
return secs*1000 + msecs
def splitAndFilter(value, separator):
items = str(value).split(separator)
ret = []
for item in items:
item = str(item).strip()
if len(item) == 0:
continue
ret += [item]
return ret
def isFloat(value):
try:
float(value)
return True
except ValueError:
return False
def strToFloat(value):
value = str(value).strip()
if len(value) == 0:
return None
value = value.replace(",", ".")
try:
return float(value)
except ValueError:
return None | {
"repo_name": "dayitv89/sim-module",
"path": "lib/sim900/amsharedmini.py",
"copies": "2",
"size": "1135",
"license": "mit",
"hash": -8608614065198607000,
"line_mean": 17.9333333333,
"line_max": 40,
"alpha_frac": 0.5612334802,
"autogenerated": false,
"ratio": 3.770764119601329,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.008416083395933008,
"num_lines": 60
} |
__author__ = 'Bojan Delic <bojan@delic.in.rs>'
__date__ = 'Aug 21, 2013'
__copyright__ = 'Copyright (c) 2013 Bojan Delic'
import weakref
from functools import partial
from Queue import Queue
from threading import Lock
from collections import defaultdict
import wpf
from System import TimeSpan
from System.Windows.Input import ICommand
from System import EventArgs
from System.Windows.Threading import DispatcherTimer
from System.ComponentModel import INotifyPropertyChanged, PropertyChangedEventArgs
from System.Collections.ObjectModel import ObservableCollection
class MvvmError(Exception):
pass
class WeakCallable(object):
'''
Weak reference to bound methods.
Because bound method is created at the moment when it is accessed every
time, it will be garbage collected very soon, even if object it is bound
to is not garbage collected. This class holds weak references to
methods `im_self` and `im_func` that will not be garbage collected
until `self` of the method is alive.
'''
def __init__(self, func, on_collect=None):
'''
Both `on_func_collect` and `on_self_collect` should accept single
parameter that will be instance of :class:`.WeakCallable` that died.
:param callable func:
Methods to create weak reference for.
:param callable on_collect:
Callable that will be called when function is garbage collected.
'''
self._ext_on_collect = on_collect
if hasattr(func, 'im_func'): # if this is method
self._func = weakref.ref(func.im_func)
self._obj = weakref.ref(func.im_self, self._on_collect)
else:
self._func = weakref.ref(func, self._on_collect)
self._obj = None
def __call__(self, *args, **kwargs):
if self._obj is not None:
cl = self._func()
obj = self._obj()
if cl is not None and obj is not None:
return cl(obj, *args, **kwargs)
else:
raise weakref.ReferenceError('Object no longer available')
else:
cl = self._func()
if cl is not None:
return cl(*args, **kwargs)
else:
raise weakref.ReferenceError('Function no longer available')
def _on_collect(self, ref):
if self._ext_on_collect is not None:
self._ext_on_collect(self)
class _Messenger(object):
'''
Thread-safe messenger that ensures that all message handlers are executed
in main dispatcher thread.
This class should be used as singleton. It is not enforced, but recomanded
way of getting instance is by using :meth:`_Messenger.instance` class
method.
'''
_instance = None
@classmethod
def instance(cls, interval=5):
'''
Returns existing instance of messenger. If one does not exist it will
be created and returned.
:param int interval:
Number of miliseconds that represents interval when messages will
be processed.
Note that this parameter will be used only the first time when
instance is requested, every other time it will be ignored
because existing instance of :class:`._Messenger` is returned.
'''
if not cls._instance:
cls._instance = _Messenger(interval)
return cls._instance
def __init__(self, interval=5):
'''
:param int interval:
Number of milliseconds that represents interval when messages will
be processed.
'''
self._subscribers = defaultdict(list)
self._messages = Queue()
self._lock = Lock()
self._timer = DispatcherTimer()
self._timer.Interval = TimeSpan.FromMilliseconds(5)
self._timer.Tick += self._execute
self._timer.Start()
def send(self, message, *args, **kwargs):
'''
Sends provided message to all listeners. Message is only added to
queue and will be processed on next tick.
:param Message message:
Message to send.
'''
self._messages.put((message, args, kwargs), False)
def subscribe(self, message, handler):
'''
Adds hander for specified message.
:param str message:
Name of message to subscribe to.
:param callable handler:
Handler for this message type. Handler must receive single parameter
and that parameter will be instance of sent message.
'''
with self._lock:
ref = WeakCallable(handler, self._on_collect)
self._subscribers[message].append(ref)
# TODO: Unsubscribing with WeakCallable does not work
def unsubscribe(self, message, handler):
'''
Removes handler from message listeners.
:param str message:
Name of message to unsubscribe handler from.
:param callable handler:
Callable that should be removed as handler for `message`.
'''
with self._lock:
self._subscribers[message].remove(WeakCallable(handler))
def _execute(self, sender, event_args):
'''
Event handler for timer that processes all queued messages.
'''
with self._lock:
while not self._messages.empty():
msg, args, kwargs = self._messages.get(False)
for subscriber in self._subscribers[msg]:
try:
subscriber(*args, **kwargs)
except weakref.ReferenceError:
# Reference to handler is lost and it is OK to silence it
pass
def _on_collect(self, ref):
with self._lock:
for msg in self._subscribers:
if ref in self._subscribers[msg]:
self._subscribers[msg].remove(ref)
class Signal(object):
'''Signal object for messaging.
Can be used to connect directly to an object without specifying
the message name. It works similarly to Qt Signals and Slots.
'''
def __init__(self, name=None):
'''
:param str name:
Name of signal, for easier debuging. If not provided name of
property to which signal is assigned to will be used if signal
is creates in :class:`.ViewModel` class.
'''
self._messanger = _Messenger.instance()
def connect(self, handler):
'''
Connects handler to this signal.
'''
self._messanger.subscribe(self, handler)
def disconnect(self, handler):
'''
Disconnects handler from this singal.
'''
self._messanger.unsubscribe(self, handler)
def emit(self, *args, **kwargs):
'''
Emits this signal. As result, all handlers will be invoked.
'''
self._messanger.send(self, *args, **kwargs)
def __str__(self):
return 'signal {name}'.format(name=self.name)
class notifiable(property):
'''
Decorator that replaces @property decorator by adding raising
property changed event when setter is invoked.
Example of usage::
class MyViewModel(ViewModel):
@notifiable
def foo(self):
return self._foo
@foo.setter
def foo(self, value):
self._foo = value
For simple properties without getter and setter function and with
automatic event raising :class:`.Notifiable` can be used.
Idea and initial code for this is taken from
http://gui-at.blogspot.com/2009/11/inotifypropertychanged-in-ironpython.html
'''
def __init__(self, getter):
def newgetter(slf):
try:
return getter(slf)
except AttributeError:
return None
super(notifiable, self).__init__(newgetter)
def setter(self, setter):
def newsetter(slf, newvalue):
oldvalue = self.fget(slf)
if oldvalue != newvalue:
setter(slf, newvalue)
slf.RaisePropertyChanged(setter.__name__)
return property(fget=self.fget,
fset=newsetter,
fdel=self.fdel,
doc=self.__doc__)
_OCO = ObservableCollection[object]
class List(_OCO):
'''
ObservableCollection that can be used as ordinary python :class:`list`.
'''
append = _OCO.Add
count = _OCO.Count
index = _OCO.IndexOf
insert = _OCO.Insert
remove = _OCO.Remove
def extend(self, seq):
for item in seq:
return self.Add(item)
def pop(self, index=None):
if index:
return self.RemoveAt(index)
else:
return self.RemoveAt(self.Count - 1)
def __getitem__(self, y):
return list(self)[y]
class Notifiable(object):
'''
Descriptor class that raises `PropertyChanged` event when new value is
set. For this to work, this descriptor can only be used in classes that
implements interface `INotifyPropertyChanged`
Class is designed to work with subclasses of :class:`ViewModel`
because this class implements `INotofyPropertyChanged` and adds metaclass
that discovers names of variables for raising events.
Example of usage::
class MyViewModel(ViewModel):
my_property = NotifProperty()
'''
def __init__(self, initial=None, name=None):
'''
:param initial:
Initial value of this property.
:param name:
Name of this property. If not provided and if this is used with
:class:`.ViewModel`, name will be set automatically to name
of property.
'''
self.name = name
self.initial = initial
def __get__(self, obj, objtype=None):
if obj is None:
return self
return getattr(obj, '__notifiable_%s' % self.name, self.initial)
def __set__(self, obj, value):
current = getattr(obj, '__notifiable_%s' % self.name, self.initial)
if current != value:
setattr(obj, '__notifiable_%s' % self.name, value)
obj.RaisePropertyChanged(self.name)
def __delete__(self, obj):
if hasattr(obj, '__notifiable_%s' % self.name):
delattr(obj, '__notifiable_%s' % self.name)
class ViewModelMeta(type):
'''
MetaClass that examines fields of new class and populates names of
:class:`.NotifProperty` fields to names of variables.
'''
def __new__(cls, name, bases, dct):
super_new = super(ViewModelMeta, cls).__new__
for name, val in dct.items():
if isinstance(val, (Notifiable, Signal)):
if not hasattr(val, 'name') or not val.name:
val.name = name
return super_new(cls, name, bases, dct)
class ViewModel(object, INotifyPropertyChanged):
'''
Base ViewModel class that all view-model classes should inherit from.
'''
__metaclass__ = ViewModelMeta
def __init__(self):
self.property_chaged_handlers = []
self.messenger = _Messenger.instance()
def RaisePropertyChanged(self, property_name):
'''
Raises event that property value has changed for provided property name.
:param str property_name:
Name of property whose value has changed.
'''
args = PropertyChangedEventArgs(property_name)
for handler in self.property_chaged_handlers:
handler(self, args)
def add_PropertyChanged(self, handler):
self.property_chaged_handlers.append(handler)
def remove_PropertyChanged(self, handler):
self.property_chaged_handlers.Remove(handler)
class Command(ICommand):
'''
Implementation of WPF command.
'''
def __init__(self, execute, can_execute=None):
self.execute = execute
self.can_execute = can_execute
self._can_execute_changed_handlers = []
def Execute(self, parameter):
'''
Executes handler for this command.
'''
self.execute()
def add_CanExecuteChanged(self, handler):
'''
Adds new listener to CanExecuteChanged event.
'''
self._can_execute_changed_handlers.append(handler)
def remove_CanExecuteChanged(self, handler):
'''
Removes listener for CanExecuteChanged event.
'''
self._can_execute_changed_handlers.remove(handler)
def RaiseCanExecuteChanged(self):
'''
Raises CanExecuteChanged event.
'''
for handler in self._can_execute_changed_handlers:
handler(self, EventArgs.Empty)
def CanExecute(self, parameter):
'''
Returns `True` if command can be executed, `False` otherwise.
'''
if self.can_execute:
return self.can_execute()
return True
class command(object):
'''
Decorator to that turns method to command handler. Example of usage::
class MyClass(ViewModel):
@command
def command_handler(self):
# do something
pass
@command_handler.can_execute
def command_can_execute(self):
# return True if command can execute, False otherwise
return True
'''
def __init__(self, handler, can_execute=None):
'''
:param callable handler:
Method that will be called when command executed.
:param callable can_execute:
Method that will be called when GUI needs information if command
can be executed. If not provided, default implementation always
returns `True`.
'''
self._handler = handler
self._can_execute = can_execute
self._command = None
def __get__(self, obj, objtype):
if not self._handler:
raise AttributeError('Unable to get field')
if not self._command:
self._command = Command(partial(self._handler, obj),
partial(self._can_execute, obj) if self._can_execute else None)
return self._command
def can_execute(self, can_execute):
'''
Decorator that adds function that determines if command can be executed.
Decorated function should return `True` if command can be executed
and false if it can not.
'''
self._can_execute = can_execute
| {
"repo_name": "delicb/mvvm",
"path": "mvvm.py",
"copies": "1",
"size": "14540",
"license": "bsd-2-clause",
"hash": -8600873770774272000,
"line_mean": 31.0264317181,
"line_max": 99,
"alpha_frac": 0.5988308116,
"autogenerated": false,
"ratio": 4.475223145583256,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5574053957183256,
"avg_score": null,
"num_lines": null
} |
__author__ = 'Bojan Delic <bojan@delic.in.rs>'
__date__ = 'Aug 23, 2013'
__copyright__ = 'Copyright (c) 2013 Bojan Delic'
import os
import wpf
from mvvm import ViewModel, Notifiable, command, notifiable, List
from System.Windows import Application, Window
class Person(ViewModel):
name = Notifiable()
age = Notifiable()
def __init__(self, name, age):
super(Person, self).__init__()
self.name = name
self.age = age
# Every user ViewModel should inherit from ViewModel
class MyViewModel(ViewModel):
# creation of properties whose setters automatically
# invokes PropertyChanged event. Initial value is optional.
text1 = Notifiable('initial value')
text2 = Notifiable()
elements = Notifiable(List([Person('John', 23), Person('Phil', 33)]))
@notifiable
def text3(self):
return 'Initial value for text3'
# using decorator to turn method to subclass of ICommand interface
@command
def ClickCommand(self):
self.text2 = 'This will show up after click'
for person in self.elements[1:]:
person.name = 'Bob'
self.elements.append(Person('Sam', 12))
# Just creating window and adding DataContext, nothing special here
class MyWindow(Window):
def __init__(self):
wpf.LoadComponent(self, os.path.join(os.path.dirname(__file__), 'example1.xaml'))
self.DataContext = MyViewModel()
if __name__ == '__main__':
Application().Run(MyWindow())
| {
"repo_name": "delicb/mvvm",
"path": "examples/example1.py",
"copies": "1",
"size": "1488",
"license": "bsd-2-clause",
"hash": -7874532449419773000,
"line_mean": 29.3673469388,
"line_max": 89,
"alpha_frac": 0.6552419355,
"autogenerated": false,
"ratio": 3.7293233082706765,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48845652437706766,
"avg_score": null,
"num_lines": null
} |
__author__ = 'Bojan Delic <bojan@delic.in.rs>'
__date__ = 'Aug 30, 2013'
__copyright__ = 'Copyright (c) 2013 Bojan Delic'
import os
import wpf
import time
from threading import Thread
from mvvm import ViewModel, Notifiable, command, notifiable, List
from System.Windows import Application, Window
class MyViewModel(ViewModel):
text1 = Notifiable('always showing')
text2 = Notifiable()
def __init__(self):
super(MyViewModel, self).__init__()
# subscribe to message with id 'messageId'
self.messenger.subscribe('messageId', self.on_message)
# message handler - will be executed in GUI thread
def on_message(self, content):
self.text2 = content
# Just creating window and adding DataContext, nothing special here
class MyWindow(Window):
def __init__(self):
wpf.LoadComponent(self, os.path.join(os.path.dirname(__file__), 'message_example.xaml'))
self.DataContext = MyViewModel()
# thread that wats for 3 seconds and then sends message with content
def threaded_function(messenger):
time.sleep(3)
messenger.send('messageId', 'This will show up in GUI')
t = Thread(target=threaded_function, args=(self.DataContext.messenger,))
t.start()
if __name__ == '__main__':
Application().Run(MyWindow())
| {
"repo_name": "delicb/mvvm",
"path": "examples/message_example.py",
"copies": "1",
"size": "1342",
"license": "bsd-2-clause",
"hash": -5928662593609892000,
"line_mean": 31.7317073171,
"line_max": 96,
"alpha_frac": 0.6602086438,
"autogenerated": false,
"ratio": 3.7486033519553073,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9828677440550998,
"avg_score": 0.01602691104086188,
"num_lines": 41
} |
__author__ = 'Bojan Delic <bojan@delic.in.rs>'
__date__ = 'Sep 1, 2013'
__copyright__ = 'Copyright (c) 2013 Bojan Delic'
import os
import wpf
from mvvm import ViewModel, Signal, Notifiable, command
from System.Windows import Window, Application
class MyViewModel(ViewModel):
text1 = Notifiable('always showing')
text2 = Notifiable()
# Creating signal by creating instance of class
signal = Signal()
def __init__(self):
super(MyViewModel, self).__init__()
# Subscribe to signal. This will probably be in different view model
# in real application
self.signal.connect(self.on_signal)
# signal handler - it will be all parameters provided in `emit` method
# of signal
def on_signal(self, content):
self.text2 = content
@command
def send_signal(self):
# on some event - emit signal with provided parameters
self.signal.emit('from signal')
class MyWindow(Window):
def __init__(self):
wpf.LoadComponent(self, os.path.join(os.path.dirname(__file__), 'signals_example.xaml'))
self.DataContext = MyViewModel()
if __name__ == '__main__':
Application().Run(MyWindow())
| {
"repo_name": "delicb/mvvm",
"path": "examples/signals_example.py",
"copies": "1",
"size": "1197",
"license": "bsd-2-clause",
"hash": 8433934176326417000,
"line_mean": 27.5,
"line_max": 96,
"alpha_frac": 0.649122807,
"autogenerated": false,
"ratio": 3.7523510971786833,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4901473904178683,
"avg_score": null,
"num_lines": null
} |
__author__ = "Bojan Delic <bojan@delic.in.rs>"
__mail__ = "bojan@delic.in.rs"
try:
from PyQt4 import QtGui, QtCore
except ImportError:
from PySide import QtGui, QtCore
from main_window import Ui_MainWindow
class MainWindow(QtGui.QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
#self.setFixedSize(self.width(), self.height())
statusbar = self.statusBar()
self.label = QtGui.QLabel('300')
statusbar.addPermanentWidget(self.label)
slider = QtGui.QSlider(QtCore.Qt.Horizontal, statusbar)
slider.setMinimum(50)
slider.setMaximum(1000)
slider.setValue(300)
statusbar.addPermanentWidget(slider)
slider.valueChanged.connect(self.ui.board.update_timer)
slider.valueChanged.connect(self.update_label)
self.statusBar().showMessage("Ovo je Game of Life")
self.from_survive = QtGui.QSpinBox(self.ui.toolBar)
self.from_survive.setMaximum(6)
self.from_survive.setMinimum(1)
self.from_survive.setValue(2)
self.ui.toolBar.addSeparator()
self.ui.toolBar.addWidget(QtGui.QLabel('From survive: '))
self.ui.toolBar.addWidget(self.from_survive)
self.to_survive = QtGui.QSpinBox(self.ui.toolBar)
self.to_survive.setMaximum(7)
self.to_survive.setMinimum(2)
self.to_survive.setValue(3)
self.ui.toolBar.addSeparator()
self.ui.toolBar.addWidget(QtGui.QLabel('To survive: '))
self.ui.toolBar.addWidget(self.to_survive)
self.come_to_life = QtGui.QSpinBox(self.ui.toolBar)
self.come_to_life.setMaximum(7)
self.come_to_life.setMinimum(2)
self.come_to_life.setValue(3)
self.ui.toolBar.addSeparator()
self.ui.toolBar.addWidget(QtGui.QLabel('Come to life: '))
self.ui.toolBar.addWidget(self.come_to_life)
self.from_survive.valueChanged.connect(self.ui.board.scene.matrix.set_from_survive)
self.to_survive.valueChanged.connect(self.ui.board.scene.matrix.set_to_survive)
self.come_to_life.valueChanged.connect(self.ui.board.scene.matrix.set_come_to_life)
self.ui.board.scene.matrix.changed.connect(self.update_statusbar)
self.ui.board.scene.matrix.reseted.connect(self.update_statusbar)
def update_statusbar(self):
self.ui.statusBar.showMessage('Live cells: %d' %
len(self.ui.board.scene.matrix.get_live_cells()))
def update_label(self, value):
self.label.setText(str(value))
@QtCore.Slot()
def on_actionSave_triggered(self):
file_name = QtGui.QFileDialog.getSaveFileName(self)
f = open(file_name, 'w')
f.write(self.ui.board.scene.matrix.to_string())
@QtCore.Slot()
def on_actionOpen_triggered(self):
from gol import GOLMatrix
f = QtGui.QFileDialog.getOpenFileName(self)
self.ui.board.scene.set_matrix(GOLMatrix.from_string(open(f, 'r').read()))
self.ui.board.scene.matrix.reseted.emit()
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())
| {
"repo_name": "delicb/GameOfLife",
"path": "gol/main.py",
"copies": "1",
"size": "3293",
"license": "mit",
"hash": 6385673163610931000,
"line_mean": 35.1868131868,
"line_max": 91,
"alpha_frac": 0.6532037656,
"autogenerated": false,
"ratio": 3.2668650793650795,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9413947483655887,
"avg_score": 0.0012242722618386766,
"num_lines": 91
} |
__author__ = "Bojan Delic <bojan@delic.in.rs>"
__mail__ = "bojan@delic.in.rs"
try:
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import Qt
except ImportError:
from PySide import QtGui, QtCore
from PySide.QtCore import Qt
class GOLMatrix(QtCore.QObject):
# TODO: How to merge these two signals into one signal with parameter
# overload (something like clicked() and clicked(bool))
changed = QtCore.Signal(dict)
reseted = QtCore.Signal()
def __init__(self):
super(GOLMatrix, self).__init__()
self.from_survive = 2
self.to_survive = 3
self.come_to_life = 3
self.cur_population = set()
self.next_population = set()
@QtCore.Slot(int)
def set_from_survive(self, from_survive):
self.from_survive = from_survive
@QtCore.Slot(int)
def set_to_survive(self, to_survive):
self.to_survive = to_survive
@QtCore.Slot(int)
def set_come_to_life(self, come_to_life):
self.come_to_life = come_to_life
def is_alive(self, x, y):
''' Returns `True` if cell (x, y) is alive, `False` otherwise.'''
return (x, y) in self.cur_population
def set_alive(self, x, y):
''' Marks cell (x, y) as alive.'''
if not self.is_alive(x, y):
self.cur_population.add((x, y))
self.changed.emit({(x, y): True})
def set_dead(self, x, y):
''' Kills cell (x, y) '''
if self.is_alive(x, y):
self.cur_population.remove((x, y))
self.changed.emit({(x, y): False})
def get_neighbours(self, x, y):
''' Returns all neighbors of cell (x, y).'''
return ((x-1, y-1), (x, y-1), (x+1, y-1),
(x+1, y), (x+1, y+1), (x, y+1),
(x-1, y+1), (x-1, y))
def get_live_cells(self):
''' Returns all alive cells.'''
return self.cur_population
def count_live_neighbours(self, x, y):
''' Returns number of alive neighbors of cell (x, y). '''
return sum(map(lambda coord: self.is_alive(coord[0], coord[1]), self.get_neighbours(x, y)))
def get_next_state(self, x, y):
''' Returns state of cell (x, y) for next iteration.
Return `True` if cell should be alive, `False` otherwise.'''
live_neighbours = self.count_live_neighbours(x, y)
return ((self.is_alive(x, y) and self.from_survive <= live_neighbours <= self.to_survive) or
(not self.is_alive(x, y) and live_neighbours == self.come_to_life))
def reset(self):
self.cur_population = set()
self.reseted.emit()
def shrink_world(self):
''' Kills all cells that are not visible on canvas.
Current implementation kill all cells that are not in (-3, -3, 53, 83),
but this should be done in respect to visible area on screen.
'''
def should_survive(cell):
return cell[0] > -3 and cell[0] < 83 and cell[1] > -3 and cell[1] < 53
self.cur_population = set(filter(should_survive, self.cur_population))
def next_iteration(self):
''' Calculates state of next generation.. '''
# TODO: This should be optimized. For only a few hundred alive cells
# show down ins visible.
self.next_population = set()
checked = set() # no need to check cell that are already checked
# for every live cell check if its state should be changed or state
# of its neighbors
for live in self.get_live_cells():
for neighbour in self.get_neighbours(*live):
if neighbour in checked:
continue
if not neighbour in self.next_population and self.get_next_state(*neighbour):
self.next_population.add(neighbour)
checked.add(neighbour)
self.cur_population, self.next_population = self.next_population, self.cur_population
self.shrink_world()
self.reseted.emit()
def to_string(self):
# TODO: Remember `from_survive`, `to_survive` and `come_to_life`
import pprint
return pprint.pformat(self.get_live_cells())
@classmethod
def from_string(cls, s):
m = GOLMatrix()
m.cur_population = eval(s)
return m
class Cell(QtGui.QGraphicsItem):
def __init__(self, *args, **kwargs):
self.size = kwargs.pop('size')
super(Cell, self).__init__(*args, **kwargs)
def boundingRect(self):
return QtCore.QRectF(0, 0, self.size, self.size)
def shape(self):
path = QtGui.QPainterPath()
path.addRect(self.boundingRect())
return path
def paint(self, painter, options, widget):
painter.setBrush(Qt.black)
# TODO: Better way to determine offset?
painter.drawEllipse(3, 3, self.size - 6, self.size - 6)
class Board(QtGui.QGraphicsScene):
def __init__(self, *args, **kwargs):
self.border_width = kwargs.pop('border_width')
self.square_size = kwargs.pop('square_size')
super(Board, self).__init__(*args, **kwargs)
self.set_matrix(GOLMatrix())
def set_matrix(self, matrix):
self.matrix = matrix
self.matrix.reseted.connect(self.redo_all)
self.matrix.changed.connect(self.redo_part)
@QtCore.Slot(dict)
def redo_part(self, part):
for (x, y), value in part.items():
if value:
self.add_cell(x, y)
else:
self.remove_cell(x, y)
@QtCore.Slot()
def redo_all(self):
''' Redraws scene. '''
self.clear()
for x, y in self.matrix.get_live_cells():
self.add_cell(x, y)
def next_iteration(self):
''' Requests form matrix to calculate next iteration.'''
self.matrix.next_iteration()
def reset(self):
''' Resets state (kills all cells)'''
self.matrix.reset()
def get_postion(self, x, y):
''' Returns position of cell (x, y) in scene coordinate system.'''
return QtCore.QPointF(x*self.square_size+self.border_width,
y*self.square_size+self.border_width)
def add_cell(self, x, y):
''' Adds cell to (x, y) coordinates.'''
item = Cell(size=self.square_size)
item.setPos(self.get_postion(x, y))
self.addItem(item)
def remove_cell(self, x, y):
''' Removes cell from (x, y) coordinates.'''
self.removeItem(self.itemAt(self.get_postion(x, y)))
class BoardView(QtGui.QGraphicsView):
def __init__(self, *args, **kwargs):
super(BoardView, self).__init__(*args, **kwargs)
self.setCacheMode(self.CacheBackground)
#self.setViewportUpdateMode(self.BoundingRectViewportUpdate)
self.setRenderHint(QtGui.QPainter.Antialiasing)
# TODO: Take this from settings
self.square_size = 20
self.border_width = 5
# Start from top left corner
self.setAlignment(Qt.AlignLeft | Qt.AlignTop)
# No need for scroll bar
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.scene = Board(self, square_size=self.square_size, border_width=self.border_width)
self.setScene(self.scene)
self.timer = QtCore.QTimer(self)
self.timer.setInterval(300)
self.timer.timeout.connect(self.scene.next_iteration)
def mousePressEvent(self, event):
pos = self.mapToScene(event.pos())
item = self.scene.itemAt(pos)
x = int((pos.x() - self.border_width) / self.square_size)
y = int((pos.y() - self.border_width) / self.square_size)
if item:
self.scene.matrix.set_dead(x, y)
else:
self.scene.matrix.set_alive(x, y)
super(BoardView, self).mousePressEvent(event)
def drawBackground(self, painter, rect):
''' Background drawing. '''
painter.setPen(Qt.DotLine)
# vertical lines
for i in xrange(int(rect.left() + self.border_width),
int(rect.right() - self.border_width),
self.square_size):
painter.drawLine(i, rect.bottom() + self.border_width, i,
rect.top() - self.border_width)
# horizontal lines
for i in xrange(int(rect.top() + self.border_width),
int(rect.bottom() - self.border_width),
self.square_size):
painter.drawLine(rect.left() + self.border_width, i,
rect.right() - self.border_width, i)
painter.setPen(QtGui.QPen(Qt.black, self.border_width, Qt.SolidLine,
Qt.RoundCap, Qt.RoundJoin))
border = QtCore.QRectF(rect.left() + self.border_width,
rect.top() + self.border_width,
rect.width() - 2*self.border_width,
rect.height() - 2*self.border_width)
painter.drawRect(border)
def resizeEvent(self, event):
# Fixes start of coordinate system to top-left corner of view
self.setSceneRect(QtCore.QRectF(0, 0, self.width(), self.height()))
super(BoardView, self).resizeEvent(event)
def update_timer(self, value):
self.timer.setInterval(value)
def start(self):
self.timer.start()
def stop(self):
self.timer.stop()
def reset(self):
self.stop()
self.scene.reset()
| {
"repo_name": "delicb/GameOfLife",
"path": "gol/gol.py",
"copies": "1",
"size": "9519",
"license": "mit",
"hash": -2777308220168581600,
"line_mean": 34.1254612546,
"line_max": 100,
"alpha_frac": 0.5812585356,
"autogenerated": false,
"ratio": 3.547894148341409,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4629152683941409,
"avg_score": null,
"num_lines": null
} |
__author__ = 'Bojan Delic <bojan@delic.in.rs>'
__date__ = '02 January 2013'
__copyright__ = 'Copyright (c) 2013 Bojan Delic'
from samovar.commander import BaseCommand
from ._parsing import HgStyle, HgLexer, PARSERS
class Command(BaseCommand):
'''Performs hg diff command on repositories.
Note that using --rev or --change options does not make sense without --repo option,
because every repository has different changesets.
But these options can be useful if used with tag that are present in every repository.
'''
option_list = BaseCommand.option_list + (
('r, rev', {'action': 'store', 'dest': 'revision', 'help': 'Revision.'}),
('c, change', {'action': 'store', 'help': 'Change made by revision.'}),
('a, text', {'action': 'store_true', 'help': 'Treat all files as text.'}),
('g, git', {'action': 'store_true', 'help': 'Use git extended diff format.'}),
('p, show-function', {'action': 'store_true', 'help': 'Show which function each change is in.'}),
('reverse', {'action': 'store_true', 'help': 'Produce diff that undoes the changes.'}),
('w, ignore-all-space', {'action': 'store_true', 'help': 'Ignore white space when comparing lines'}),
('b, ignore-space-change', {'action': 'store_true', 'help': 'Ignore changes in amount of white space.'}),
('B, ignore-blank-lines', {'action': 'store_true', 'help': 'Ignore changes whose lines are all blank.'}),
('stat', {'action': 'store_true', 'help': 'Output diffstat-style summary of changes.'}),
('U, unified', {
'action' : 'store',
'type' : int,
'dest' : 'unified',
'default' : -1,
'help' : 'Number of lines of context to show.'
}),
)
Style = HgStyle
Lexer = HgLexer
LexerConfig = {
'parse' : True,
'parser' : PARSERS['diff'],
'indent' : 0,
}
def handle(self, *args, **kwargs):
for repo in self.config.repositories:
status, output, error = repo.diff(**kwargs)
self.ui.report(repo, status, {'output': output, 'error': error})
| {
"repo_name": "alefnula/samovar",
"path": "src/samovar/commands/scm/diff.py",
"copies": "1",
"size": "2318",
"license": "bsd-3-clause",
"hash": -388216031497156700,
"line_mean": 46.2916666667,
"line_max": 114,
"alpha_frac": 0.5405522002,
"autogenerated": false,
"ratio": 3.889261744966443,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9882306142343241,
"avg_score": 0.009501560564640408,
"num_lines": 48
} |
__author__ = 'Bojan Delic <bojan@delic.in.rs>'
__date__ = '02 January 2013'
__copyright__ = 'Copyright (c) 2013 Bojan Delic'
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
from samovar.commander import BaseCommand
from tea.utils.crypto import encrypt
class Command(BaseCommand):
'''
Manages repository credentials.
Usage:
credentials set
credentials list
'''
def handle(self, *args, **kwargs):
if len(args) == 1 and args[0] == 'set':
url = self.ui.ask('Url: ')
parsed = urlparse.urlparse(url)
url = parsed.netloc if parsed.netloc else parsed.path
username = self.ui.ask('Username: ')
password = encrypt(self.ui.ask('Password: ', True))
data = {
'url': url,
'username': username,
'password': password,
}
current_creds = self.config.get(self.id, None)
if current_creds:
for i, cred in enumerate(current_creds):
if cred['url'] == url:
self.config.delete('%s.%s' % (self.id, i))
else:
self.config.set(self.id, [])
self.config.insert(self.id, data)
elif len(args) == 1 and args[0] == 'list':
for cred in self.config.get(self.id, []):
self.ui.info('%s -> %s' % (cred['url'], cred['username']))
else:
self.print_usage()
| {
"repo_name": "alefnula/samovar",
"path": "src/samovar/commands/repo/credentials.py",
"copies": "1",
"size": "1588",
"license": "bsd-3-clause",
"hash": -3281368595331230000,
"line_mean": 29.137254902,
"line_max": 74,
"alpha_frac": 0.4981108312,
"autogenerated": false,
"ratio": 4.082262210796915,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.001916683826193256,
"num_lines": 51
} |
import collections
import sys
from astropy.coordinates import SkyCoord
from astropy import units as u
from processing_components.calibration.operations import apply_gaintable, create_gaintable_from_blockvisibility, qa_gaintable
from processing_components.visibility.base import create_visibility, copy_visibility
from data_models.memory_data_models import ReceptorFrame
from processing_components.image.deconvolution import deconvolve_cube, restore_cube
from processing_components.imaging.base import create_image_from_visibility, predict_2d, invert_2d
from processing_components.imaging.base import advise_wide_field
from processing_components.simulation.testing_support import create_test_image, create_low_test_image_from_gleam, simulate_gaintable
from processing_components.simulation.configurations import create_named_configuration
from data_models.polarisation import PolarisationFrame
from processing_components.visibility.base import create_blockvisibility
from workflows.serial.imaging.imaging_serial import invert_list_serial_workflow, predict_list_serial_workflow
from processing_components.image.operations import qa_image
from processing_components.visibility.coalesce import convert_visibility_to_blockvisibility, convert_blockvisibility_to_visibility
from processing_components.calibration.calibration import solve_gaintable
from workflows.serial.pipelines.pipeline_serial import ical_list_serial_workflow
from data_models.data_model_helpers import export_image_to_hdf5
from src.arlwrap_support import *
import logging
import os
results_dir = './results'
os.makedirs(results_dir, exist_ok=True)
log = logging.getLogger()
log.setLevel(logging.INFO)
log.addHandler(logging.StreamHandler(sys.stdout))
arl_error = 0
def handle_error(*args):
global arl_error
if(args[0] != ""):
arl_error = -1
print(args[0],"\n",args[1],"\n",args[2])
ff.cdef("""
typedef struct {
size_t nvis;
int npol;
void *data;
char *phasecentre;
} ARLVis;
""")
ff.cdef("""
typedef struct {
size_t nrows;
void *data;
} ARLGt;
""")
ff.cdef("""
typedef struct {
char *confname;
double pc_ra;
double pc_dec;
double *times;
int ntimes;
double *freqs;
int nfreqs;
double *channel_bandwidth;
int nchanwidth;
int nbases;
int nant;
int npol;
int nrec;
double rmax;
char *polframe;
} ARLConf;
""")
ff.cdef("""
typedef struct {
int vis_slices;
int npixel;
double cellsize;
double guard_band_image;
double delA;
int wprojection_planes;
} ARLadvice ;
""")
#@ff.callback("void (*)(const ARLVis *, ARLVis *, bool)")
#def arl_copy_visibility_ffi(visin, visout, zero):
# """
# Wrap of arl.visibility.base.copy_visibility
# """
# # Extra comments becasue this is an example.
# #
# # Convert the input visibilities into the ARL structure
# nvisin=cARLVis(visin)
#
# # Call the ARL function
# tvis=copy_visibility(nvisin, zero=zero)
#
# # Copy the result into the output buffer
# visout.npol=visin.npol
# visout.nvis=visin.nvis
# nvisout=cARLVis(visout)
# numpy.copyto(nvisout, tvis)
#
#
#arl_copy_visibility=collections.namedtuple("FFIX", "address")
#arl_copy_visibility.address=int(ff.cast("size_t", arl_copy_visibility_ffi))
@ff.callback("int (*)()")
def arl_handle_error_ffi():
global arl_error
return arl_error
arl_handle_error=collections.namedtuple("FFIX", "address")
arl_handle_error.address=int(ff.cast("size_t", arl_handle_error_ffi))
@ff.callback("void (*)(ARLConf *, const ARLVis *, ARLVis *, int)", onerror=handle_error)
def arl_copy_visibility_ffi(lowconfig, vis_in, vis_out, zero_in):
# Convert the input blockvisibilities into the ARL structure
if zero_in == 0:
zero = True
else:
zero = False
# Create configuration object
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
# Re-create input blockvisibility object
times = numpy.frombuffer(ff.buffer(lowconfig.times, 8*lowconfig.ntimes), dtype='f8', count=lowconfig.ntimes)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
c_visin = cARLVis(vis_in)
py_visin = helper_create_blockvisibility_object(c_visin, frequency, channel_bandwidth, lowcore)
py_visin.phasecentre = load_phasecentre(vis_in.phasecentre)
py_visin.configuration = lowcore
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
py_visin.polarisation_frame = PolarisationFrame(polframe)
# Call the ARL function
py_visout=copy_visibility(py_visin, zero=zero)
# Copy the result into the output buffer
vis_out.npol=vis_in.npol
vis_out.nvis=vis_in.nvis
py_vis_out = cARLVis(vis_out)
numpy.copyto(py_vis_out, py_visout.data)
store_phasecentre(vis_out.phasecentre, py_visin.phasecentre)
arl_copy_visibility=collections.namedtuple("FFIX", "address")
arl_copy_visibility.address=int(ff.cast("size_t", arl_copy_visibility_ffi))
@ff.callback("void (*)(ARLConf *, const ARLVis *, ARLVis *, int)", onerror=handle_error)
def arl_copy_blockvisibility_ffi(lowconfig, blockvis_in, blockvis_out, zero_in):
# Convert the input blockvisibilities into the ARL structure
if zero_in == 0:
zero = True
else:
zero = False
# Create configuration object
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
# Re-create input blockvisibility object
times = numpy.frombuffer(ff.buffer(lowconfig.times, 8*lowconfig.ntimes), dtype='f8', count=lowconfig.ntimes)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
c_blockvisin = cARLBlockVis(blockvis_in, lowconfig.nant, lowconfig.nfreqs)
py_blockvisin = helper_create_blockvisibility_object(c_blockvisin, frequency, channel_bandwidth, lowcore)
py_blockvisin.phasecentre = load_phasecentre(blockvis_in.phasecentre)
py_blockvisin.configuration = lowcore
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
py_blockvisin.polarisation_frame = PolarisationFrame(polframe)
# Call the ARL function
py_blockvisout=copy_visibility(py_blockvisin, zero=zero)
# Copy the result into the output buffer
blockvis_out.npol=blockvis_in.npol
blockvis_out.nvis=blockvis_in.nvis
py_blockvis_out = cARLBlockVis(blockvis_out, lowconfig.nant, lowconfig.nfreqs)
numpy.copyto(py_blockvis_out, py_blockvisout.data)
store_phasecentre(blockvis_out.phasecentre, py_blockvisin.phasecentre)
arl_copy_blockvisibility=collections.namedtuple("FFIX", "address")
arl_copy_blockvisibility.address=int(ff.cast("size_t", arl_copy_blockvisibility_ffi))
@ff.callback("void (*)(ARLConf *, ARLVis *)", onerror=handle_error)
def arl_set_visibility_data_to_zero_ffi(lowconfig, vis_in):
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
times = numpy.frombuffer(ff.buffer(lowconfig.times, 8*lowconfig.ntimes), dtype='f8', count=lowconfig.ntimes)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
c_visin = cARLVis(vis_in)
py_visin = helper_create_visibility_object(c_visin)
py_visin.phasecentre = load_phasecentre(vis_in.phasecentre)
py_visin.configuration = lowcore
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
py_visin.polarisation_frame = PolarisationFrame(polframe)
py_visin.data['vis'][...] = 0.0
arl_set_visibility_data_to_zero=collections.namedtuple("FFIX", "address")
arl_set_visibility_data_to_zero.address=int(ff.cast("size_t", arl_set_visibility_data_to_zero_ffi))
@ff.callback("void (*)(ARLConf *, const ARLVis *, const ARLVis *, ARLVis *, int)", onerror=handle_error)
def arl_manipulate_visibility_data_ffi(lowconfig, vis1_in, vis2_in, vis_out, operation):
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
times = numpy.frombuffer(ff.buffer(lowconfig.times, 8*lowconfig.ntimes), dtype='f8', count=lowconfig.ntimes)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
c_vis1in = cARLVis(vis1_in)
py_vis1in = helper_create_visibility_object(c_vis1in)
py_vis1in.phasecentre = load_phasecentre(vis1_in.phasecentre)
py_vis1in.configuration = lowcore
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
py_vis1in.polarisation_frame = PolarisationFrame(polframe)
c_vis2in = cARLVis(vis2_in)
py_vis2in = helper_create_visibility_object(c_vis2in)
py_vis2in.phasecentre = load_phasecentre(vis2_in.phasecentre)
py_vis2in.configuration = lowcore
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
py_vis2in.polarisation_frame = PolarisationFrame(polframe)
c_visout = cARLVis(vis_out)
py_visout = helper_create_visibility_object(c_visout)
py_visout.phasecentre = load_phasecentre(vis_out.phasecentre)
py_visout.configuration = lowcore
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
py_visout.polarisation_frame = PolarisationFrame(polframe)
print("arl_manipulate_visibility_data opcode: ", operation)
if operation == 0: # Add
print("arl_manipulate_visibility_data: adding")
py_visout.data['vis'] = py_vis1in.data['vis'] + py_vis2in.data['vis']
elif operation == 1: # Subtract
print("arl_manipulate_visibility_data: subtracting")
py_visout.data['vis'] = py_vis1in.data['vis'] - py_vis2in.data['vis']
elif operation == 2: # Multiply
print("arl_manipulate_visibility_data: multiplying")
py_visout.data['vis'] = py_vis1in.data['vis'] * py_vis2in.data['vis']
elif operation == 3: # Divide
print("arl_manipulate_visibility_data: dividing")
py_visout.data['vis'] = py_vis1in.data['vis'] / py_vis2in.data['vis']
else:
py_visout.data['vis'][...] = 0.0
print("arl_manipulate_visibility_data np.sum(vis.data): ", numpy.sum(py_visout.data['vis']), numpy.sum(py_vis1in.data['vis']), numpy.sum(py_vis2in.data['vis']))
arl_manipulate_visibility_data=collections.namedtuple("FFIX", "address")
arl_manipulate_visibility_data.address=int(ff.cast("size_t", arl_manipulate_visibility_data_ffi))
ff.cdef("""
typedef struct {
size_t size;
int data_shape[4];
void *data;
char *wcs;
char *polarisation_frame;
} Image;
""")
@ff.callback("void (*)(Image*, Image*)")
def arl_add_to_model_ffi(model, res):
c_model = cImage(model)
c_res = cImage(res)
c_model.data += c_res.data
arl_add_to_model=collections.namedtuple("FFIX", "address")
arl_add_to_model.address=int(ff.cast("size_t", arl_add_to_model_ffi))
@ff.callback("void (*)(ARLConf *, ARLVis *)", onerror=handle_error)
def arl_create_visibility_ffi(lowconfig, c_res_vis):
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
# Temp fix for ffi_demo
if lowconfig.rmax < 1.0e-5 :
lowcore = create_named_configuration(lowcore_name)
else:
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
times = numpy.frombuffer(ff.buffer(lowconfig.times, 8*lowconfig.ntimes), dtype='f8', count=lowconfig.ntimes)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
print(lowcore_name)
print("Times: ", times)
print("Freqs: ", frequency)
print("BW : ", channel_bandwidth)
print("PCentre: ", lowconfig.pc_ra, lowconfig.pc_dec)
phasecentre = SkyCoord(ra=lowconfig.pc_ra * u.deg, dec=lowconfig.pc_dec*u.deg, frame='icrs',
equinox='J2000')
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
vt = create_visibility(lowcore, times, frequency,
channel_bandwidth=channel_bandwidth, weight=1.0,
phasecentre=phasecentre,
polarisation_frame=PolarisationFrame(polframe))
py_res_vis = cARLVis(c_res_vis)
numpy.copyto(py_res_vis, vt.data)
store_phasecentre(c_res_vis.phasecentre, phasecentre)
arl_create_visibility=collections.namedtuple("FFIX", "address")
arl_create_visibility.address=int(ff.cast("size_t", arl_create_visibility_ffi))
@ff.callback("void (*)(ARLConf *, ARLVis *)", onerror=handle_error)
def arl_create_blockvisibility_ffi(lowconfig, c_res_vis):
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
print(lowconfig.rmax)
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
times = numpy.frombuffer(ff.buffer(lowconfig.times, 8*lowconfig.ntimes), dtype='f8', count=lowconfig.ntimes)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
print(lowcore_name)
print("Times: ", times)
print("Freqs: ", frequency)
print("BW : ", channel_bandwidth)
print("PCentre: ", lowconfig.pc_ra, lowconfig.pc_dec)
phasecentre = SkyCoord(ra=lowconfig.pc_ra * u.deg, dec=lowconfig.pc_dec*u.deg, frame='icrs',
equinox='J2000')
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
print("Polarisation frame: ", polframe)
vt = create_blockvisibility(lowcore, times, frequency=frequency,
channel_bandwidth=channel_bandwidth, weight=1.0,
phasecentre=phasecentre,
polarisation_frame=PolarisationFrame(polframe))
py_res_vis = cARLBlockVis(c_res_vis, lowconfig.nant, lowconfig.nfreqs)
numpy.copyto(py_res_vis, vt.data)
store_phasecentre(c_res_vis.phasecentre, phasecentre)
receptor_frame = ReceptorFrame(vt.polarisation_frame.type)
lowconfig.nrec = receptor_frame.nrec
arl_create_blockvisibility=collections.namedtuple("FFIX", "address")
arl_create_blockvisibility.address=int(ff.cast("size_t", arl_create_blockvisibility_ffi))
@ff.callback("void (*)(ARLConf *, const ARLVis *, const ARLVis *, long long int *, ARLVis *)", onerror=handle_error)
def arl_convert_visibility_to_blockvisibility_ffi(lowconfig, vis_in, blockvis_in, cindex_in, blockvis_out):
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
times = numpy.frombuffer(ff.buffer(lowconfig.times, 8*lowconfig.ntimes), dtype='f8', count=lowconfig.ntimes)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
cindex_size = lowconfig.nant*lowconfig.nant*lowconfig.nfreqs*lowconfig.ntimes
py_cindex = numpy.frombuffer(ff.buffer(cindex_in, 8*cindex_size), dtype='int', count=cindex_size)
c_visin = cARLVis(vis_in)
py_visin = helper_create_visibility_object(c_visin)
py_visin.phasecentre = load_phasecentre(vis_in.phasecentre)
py_visin.configuration = lowcore
py_visin.cindex = py_cindex
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
py_visin.polarisation_frame = PolarisationFrame(polframe)
c_blockvisin = cARLBlockVis(blockvis_in, lowconfig.nant, lowconfig.nfreqs)
py_blockvisin = helper_create_blockvisibility_object(c_blockvisin, frequency, channel_bandwidth, lowcore)
py_blockvisin.phasecentre = load_phasecentre(blockvis_in.phasecentre)
py_blockvisin.configuration = lowcore
py_blockvisin.polarisation_frame = PolarisationFrame(polframe)
py_visin.blockvis = py_blockvisin
py_blockvisout = convert_visibility_to_blockvisibility(py_visin)
print("convert_visibility_to_blockvisibility np.sum(block_vis.data): ", numpy.sum(py_blockvisout.data['vis']))
py_blockvis_out = cARLBlockVis(blockvis_out, lowconfig.nant, lowconfig.nfreqs)
numpy.copyto(py_blockvis_out, py_blockvisout.data)
store_phasecentre(blockvis_out.phasecentre, py_blockvisin.phasecentre)
arl_convert_visibility_to_blockvisibility=collections.namedtuple("FFIX", "address")
arl_convert_visibility_to_blockvisibility.address=int(ff.cast("size_t", arl_convert_visibility_to_blockvisibility_ffi))
@ff.callback("void (*)(ARLConf *, const ARLVis *, ARLVis *, long long int *, ARLVis *)", onerror=handle_error)
def arl_convert_blockvisibility_to_visibility_ffi(lowconfig, blockvis_in, vis_out, cindex_out, blockvis_out):
# Create configuration object
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
# Link cindex memory objects
cindex_size = lowconfig.nant*lowconfig.nant*lowconfig.nfreqs*lowconfig.ntimes
py_cindex = numpy.frombuffer(ff.buffer(cindex_out, 8*cindex_size), dtype='int', count=cindex_size)
# Re-create input blockvisibility object
times = numpy.frombuffer(ff.buffer(lowconfig.times, 8*lowconfig.ntimes), dtype='f8', count=lowconfig.ntimes)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
c_blockvisin = cARLBlockVis(blockvis_in, lowconfig.nant, lowconfig.nfreqs)
py_blockvisin = helper_create_blockvisibility_object(c_blockvisin, frequency, channel_bandwidth, lowcore)
py_blockvisin.phasecentre = load_phasecentre(blockvis_in.phasecentre)
py_blockvisin.configuration = lowcore
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
py_blockvisin.polarisation_frame = PolarisationFrame(polframe)
# Call arl.coalesce::convert_blockvisibility_to_visibility()
vis = convert_blockvisibility_to_visibility(py_blockvisin)
# Copy vis.data to C visibility vis_out.data
py_vis = cARLVis(vis_out)
numpy.copyto(py_vis, vis.data)
store_phasecentre(vis_out.phasecentre, py_blockvisin.phasecentre)
# Copy vis.blockvis.data to C blockvisibility blockvis_out.data
py_blockvis_out = cARLBlockVis(blockvis_out, lowconfig.nant, lowconfig.nfreqs)
numpy.copyto(py_blockvis_out, vis.blockvis.data)
# Copy vis.cindex to cindex_out
numpy.copyto(py_cindex, vis.cindex)
print("convert_blockvisibility_to_visibility np.sum(vis.data): ", numpy.sum(vis.data['vis']))
arl_convert_blockvisibility_to_visibility=collections.namedtuple("FFIX", "address")
arl_convert_blockvisibility_to_visibility.address=int(ff.cast("size_t", arl_convert_blockvisibility_to_visibility_ffi))
@ff.callback("void (*)(ARLConf *, const ARLVis *, ARLGt *)", onerror=handle_error)
def arl_create_gaintable_from_blockvisibility_ffi(lowconfig, blockvis_in, gt_out):
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
times = numpy.frombuffer(ff.buffer(lowconfig.times, 8*lowconfig.ntimes), dtype='f8', count=lowconfig.ntimes)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
c_blockvisin = cARLBlockVis(blockvis_in, lowconfig.nant, lowconfig.nfreqs)
py_blockvisin = helper_create_blockvisibility_object(c_blockvisin, frequency, channel_bandwidth, lowcore)
py_blockvisin.phasecentre = load_phasecentre(blockvis_in.phasecentre)
py_blockvisin.configuration = lowcore
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
py_blockvisin.polarisation_frame = PolarisationFrame(polframe)
py_gt = create_gaintable_from_blockvisibility(py_blockvisin)
# print("create_gaintable_from_blockvisibility np.sum(gt.data): ", numpy.sum(py_gt.data['gain']))
# print(py_gt.data['gain'].shape, py_gt.data['weight'].shape, py_gt.data['residual'].shape, py_gt.data['time'].shape)
# print(py_gt.data.size, py_gt.data.itemsize)
# print(py_gt.frequency.size)
# print("create_gaintable_from_blockvisibility: ", py_gt.receptor_frame.nrec)
# receptor_frame = ReceptorFrame(py_blockvisin.polarisation_frame.type)
# pframe1 = PolarisationFrame(polframe)
# recframe1 = ReceptorFrame(pframe1.type)
# print(receptor_frame.nrec, recframe1.nrec, lowcore.receptor_frame.nrec)
c_gt_out = cARLGt(gt_out, lowconfig.nant, lowconfig.nfreqs, lowconfig.nrec)
numpy.copyto(c_gt_out, py_gt.data)
arl_create_gaintable_from_blockvisibility=collections.namedtuple("FFIX", "address")
arl_create_gaintable_from_blockvisibility.address=int(ff.cast("size_t", arl_create_gaintable_from_blockvisibility_ffi))
@ff.callback("void (*)(ARLConf *, ARLGt *)", onerror=handle_error)
def arl_simulate_gaintable_ffi(lowconfig, gt):
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
times = numpy.frombuffer(ff.buffer(lowconfig.times, 8*lowconfig.ntimes), dtype='f8', count=lowconfig.ntimes)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
polarisation_frame = PolarisationFrame(polframe)
receptor_frame = ReceptorFrame(polarisation_frame.type)
# print(lowconfig.polframe, lowconfig.nrec, receptor_frame.nrec)
c_gt = cARLGt(gt, lowconfig.nant, lowconfig.nfreqs, lowconfig.nrec)
py_gt = helper_create_gaintable_object(c_gt, frequency, receptor_frame)
py_gt.receptor_frame = receptor_frame
# print()
# print(py_gt.__dict__)
# print("simulate_gaintable 1 nrec: ", py_gt.receptor_frame.nrec)
# print(py_gt.data['gain'].shape, py_gt.data['weight'].shape, py_gt.data['residual'].shape, py_gt.data['time'].shape)
py_gt = simulate_gaintable(py_gt, phase_error = 1.0)
# py_gt = simulate_gaintable(py_gt, phase_error = 0.0)
# print("simulate_gaintable np.sum(gt.data): ", numpy.sum(py_gt.data['gain']))
# print("simulate_gaintable 2 nrec: ", py_gt.receptor_frame.nrec)
# print(py_gt.data['gain'].shape, py_gt.data['weight'].shape, py_gt.data['residual'].shape, py_gt.data['time'].shape)
numpy.copyto(c_gt, py_gt.data)
arl_simulate_gaintable=collections.namedtuple("FFIX", "address")
arl_simulate_gaintable.address=int(ff.cast("size_t", arl_simulate_gaintable_ffi))
@ff.callback("void (*)(ARLConf *, const ARLVis *, ARLGt *, ARLVis *, int )", onerror=handle_error)
def arl_apply_gaintable_ffi(lowconfig, blockvis_in, gt, blockvis_out, inverse_in):
if inverse_in == 0:
inverse = True
else:
inverse = False
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
times = numpy.frombuffer(ff.buffer(lowconfig.times, 8*lowconfig.ntimes), dtype='f8', count=lowconfig.ntimes)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
# Re-creating the input BlockVisibility object
c_blockvisin = cARLBlockVis(blockvis_in, lowconfig.nant, lowconfig.nfreqs)
py_blockvisin = helper_create_blockvisibility_object(c_blockvisin, frequency, channel_bandwidth, lowcore)
py_blockvisin.phasecentre = load_phasecentre(blockvis_in.phasecentre)
py_blockvisin.configuration = lowcore
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
py_blockvisin.polarisation_frame = PolarisationFrame(polframe)
# Re-creating GainTable object
receptor_frame = ReceptorFrame(py_blockvisin.polarisation_frame.type)
c_gt = cARLGt(gt, lowconfig.nant, lowconfig.nfreqs, lowconfig.nrec)
py_gt = helper_create_gaintable_object(c_gt, frequency, receptor_frame)
py_gt.receptor_frame = receptor_frame
# Calling apply_gaintable() function
py_blockvisout = apply_gaintable(py_blockvisin, py_gt, inverse=inverse)
# print("apply_gaintable np.sum(blockvis.data): ", numpy.sum(py_blockvisout.data['vis']))
# Copy resulting data from py_blockvisout into c_blockvisout
py_blockvis_out = cARLBlockVis(blockvis_out, lowconfig.nant, lowconfig.nfreqs)
numpy.copyto(py_blockvis_out, py_blockvisout.data)
store_phasecentre(blockvis_out.phasecentre, py_blockvisin.phasecentre)
arl_apply_gaintable=collections.namedtuple("FFIX", "address")
arl_apply_gaintable.address=int(ff.cast("size_t", arl_apply_gaintable_ffi))
@ff.callback("void (*)(ARLConf *, ARLVis *, ARLGt *, int )", onerror=handle_error)
def arl_apply_gaintable_ical_ffi(lowconfig, blockvis_in, gt, inverse_in):
if inverse_in == 0:
inverse = True
else:
inverse = False
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
times = numpy.frombuffer(ff.buffer(lowconfig.times, 8*lowconfig.ntimes), dtype='f8', count=lowconfig.ntimes)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
# Re-creating the input BlockVisibility object
c_blockvisin = cARLBlockVis(blockvis_in, lowconfig.nant, lowconfig.nfreqs)
py_blockvisin = helper_create_blockvisibility_object(c_blockvisin, frequency, channel_bandwidth, lowcore)
py_blockvisin.phasecentre = load_phasecentre(blockvis_in.phasecentre)
py_blockvisin.configuration = lowcore
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
py_blockvisin.polarisation_frame = PolarisationFrame(polframe)
# Re-creating GainTable object
receptor_frame = ReceptorFrame(py_blockvisin.polarisation_frame.type)
c_gt = cARLGt(gt, lowconfig.nant, lowconfig.nfreqs, lowconfig.nrec)
py_gt = helper_create_gaintable_object(c_gt, frequency, receptor_frame)
py_gt.receptor_frame = receptor_frame
# Calling apply_gaintable() function
py_blockvisout = apply_gaintable(py_blockvisin, py_gt, inverse=inverse)
# print("apply_gaintable np.sum(blockvis.data): ", numpy.sum(py_blockvisout.data['vis']))
# Copy resulting data from py_blockvisout back to c_blockvisin
numpy.copyto(c_blockvisin, py_blockvisout.data)
arl_apply_gaintable_ical=collections.namedtuple("FFIX", "address")
arl_apply_gaintable_ical.address=int(ff.cast("size_t", arl_apply_gaintable_ical_ffi))
@ff.callback("void (*)(ARLConf *, const ARLVis *, const ARLVis *, ARLGt *, int )", onerror=handle_error)
def arl_solve_gaintable_ical_ffi(lowconfig, blockvis_in, blockvis_pred, gt, vis_slices):
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
times = numpy.frombuffer(ff.buffer(lowconfig.times, 8*lowconfig.ntimes), dtype='f8', count=lowconfig.ntimes)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
# Re-creating the input BlockVisibility object
c_blockvisin = cARLBlockVis(blockvis_in, lowconfig.nant, lowconfig.nfreqs)
py_blockvisin = helper_create_blockvisibility_object(c_blockvisin, frequency, channel_bandwidth, lowcore)
py_blockvisin.phasecentre = load_phasecentre(blockvis_in.phasecentre)
py_blockvisin.configuration = lowcore
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
py_blockvisin.polarisation_frame = PolarisationFrame(polframe)
# Re-creating the input BlockVisibility_pred object
c_blockvispred = cARLBlockVis(blockvis_pred, lowconfig.nant, lowconfig.nfreqs)
py_blockvispred = helper_create_blockvisibility_object(c_blockvispred, frequency, channel_bandwidth, lowcore)
py_blockvispred.phasecentre = load_phasecentre(blockvis_pred.phasecentre)
py_blockvispred.configuration = lowcore
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
py_blockvispred.polarisation_frame = PolarisationFrame(polframe)
# Re-creating GainTable object
receptor_frame = ReceptorFrame(py_blockvisin.polarisation_frame.type)
c_gt = cARLGt(gt, lowconfig.nant, lowconfig.nfreqs, lowconfig.nrec)
py_gt = helper_create_gaintable_object(c_gt, frequency, receptor_frame)
py_gt.receptor_frame = receptor_frame
# Calling apply_gaintable() function
gt_out = solve_gaintable(py_blockvisin, py_blockvispred,
vis_slices=vis_slices, timeslice='auto',
algorithm='hogbom', niter=1000, fractional_threshold=0.1, threshold=0.1,
nmajor=5, gain=0.1, first_selfcal=1,
global_solution=False)
log.info(qa_gaintable(gt_out, context='Gaintable for selfcal cycle'))
numpy.copyto(c_gt, gt_out.data)
# print("apply_gaintable np.sum(blockvis.data): ", numpy.sum(py_blockvisout.data['vis']))
arl_solve_gaintable_ical=collections.namedtuple("FFIX", "address")
arl_solve_gaintable_ical.address=int(ff.cast("size_t", arl_solve_gaintable_ical_ffi))
@ff.callback("void (*)(ARLConf *, ARLVis *, ARLadvice *)", onerror=handle_error)
def arl_advise_wide_field_ffi(lowconfig, vis_in, adv):
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
c_visin = cARLBlockVis(vis_in, lowconfig.nant, lowconfig.nfreqs)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
py_visin = helper_create_blockvisibility_object(c_visin, frequency, channel_bandwidth, lowcore)
py_visin.phasecentre = load_phasecentre(vis_in.phasecentre)
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
py_visin.polarisation_frame = PolarisationFrame(polframe)
print("Index :", py_visin.data['index'])
advice=advise_wide_field(py_visin, guard_band_image=adv.guard_band_image, delA=adv.delA,
wprojection_planes=adv.wprojection_planes)
print(advice['vis_slices'], advice['npixels2'], advice['cellsize'])
adv.cellsize = advice['cellsize']
adv.vis_slices = advice['vis_slices']
adv.npixel = advice['npixels2']
arl_advise_wide_field=collections.namedtuple("FFIX", "address")
arl_advise_wide_field.address=int(ff.cast("size_t", arl_advise_wide_field_ffi))
ff.cdef("""
typedef struct {int nant, nbases;} ant_t;
""")
# Get the number of baselines for the given configuration
# WARING!!! rmax is missing ! -ToDo
@ff.callback("void (*) (char*, ant_t *)", onerror=handle_error)
def helper_get_nbases_ffi(config_name, nbases_in):
tconfig_name = str(ff.string(config_name), 'utf-8')
lowcore = create_named_configuration(tconfig_name)
nbases_in.nant = len(lowcore.xyz)
nbases_in.nbases = int(len(lowcore.xyz)*(len(lowcore.xyz)-1)/2)
print(tconfig_name,nbases_in.nant, nbases_in.nbases )
helper_get_nbases=collections.namedtuple("FFIX", "address")
helper_get_nbases.address=int(ff.cast("size_t", helper_get_nbases_ffi))
# Get the number of baselines for the given configuration
# WARING!!! rmax is missing ! -ToDo
@ff.callback("void (*) (char*, double, ant_t *)")
def helper_get_nbases_rmax_ffi(config_name, rmax, nbases_in):
tconfig_name = str(ff.string(config_name), 'utf-8')
lowcore = create_named_configuration(tconfig_name, rmax=rmax)
nbases_in.nant = len(lowcore.xyz)
nbases_in.nbases = int(len(lowcore.xyz)*(len(lowcore.xyz)-1)/2)
print(tconfig_name,nbases_in.nant, nbases_in.nbases )
helper_get_nbases_rmax=collections.namedtuple("FFIX", "address")
helper_get_nbases_rmax.address=int(ff.cast("size_t", helper_get_nbases_rmax_ffi))
@ff.callback("void (*)(ARLConf *, double, int, int *)", onerror=handle_error)
def helper_get_image_shape_multifreq_ffi(lowconfig, cellsize, npixel, c_shape):
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
print("About to start create_low_test_image_from_gleam with flux_limit = 10. to get a shape of the image")
res = create_low_test_image_from_gleam(npixel=npixel, frequency=frequency,
channel_bandwidth=channel_bandwidth, cellsize=cellsize, flux_limit = 10.)
# phasecentre=phasecentre, applybeam=True)
# res = create_test_image(frequency=frequency, cellsize=cellsize, npixel = npixel)
shape = list(res.data.shape)
# TODO fix ugly
numpy.copyto(numpy.frombuffer(ff.buffer(c_shape,4*4),dtype='i4',count=4), shape)
helper_get_image_shape_multifreq=collections.namedtuple("FFIX", "address")
helper_get_image_shape_multifreq.address=int(ff.cast("size_t", helper_get_image_shape_multifreq_ffi))
# TODO temporary until better solution found
@ff.callback("void (*)(const double *, double, int *)", onerror=handle_error)
def helper_get_image_shape_ffi(freq, cellsize, c_shape):
res = create_test_image(freq, cellsize)
shape = list(res.data.shape)
# TODO fix ugly
numpy.copyto(numpy.frombuffer(ff.buffer(c_shape,4*4),dtype='i4',count=4), shape)
helper_get_image_shape=collections.namedtuple("FFIX", "address")
helper_get_image_shape.address=int(ff.cast("size_t", helper_get_image_shape_ffi))
# TODO properly implement this routine - shouldn't be within create_test_image
#@ff.callback("void (*)(const ARLVis *, Image *)")
#def helper_set_image_params_ffi(vis, image):
# phasecentre = load_phasecentre(vis.phasecentre)
#
# py_image = cImage(image)
#
# py_image.wcs.wcs.crval[0] = phasecentre.ra.deg
# py_image.wcs.wcs.crval[1] = phasecentre.dec.deg
# py_image.wcs.wcs.crpix[0] = float(nx // 2)
# py_image.wcs.wcs.crpix[1] = float(ny // 2)
#
#helper_set_image_params=collections.namedtuple("FFIX", "address")
#helper_set_image_params.address=int(ff.cast("size_t", helper_set_image_params_ffi))
@ff.callback("void (*)(const double *, double, char*, Image *)", onerror=handle_error)
def arl_create_test_image_ffi(frequency, cellsize, c_phasecentre, out_img):
py_outimg = cImage(out_img, new=True)
res = create_test_image(frequency, cellsize)
phasecentre = load_phasecentre(c_phasecentre)
nchan, npol, ny, nx = res.data.shape
# res.wcs.wcs.crval[0] = phasecentre.ra.deg
# res.wcs.wcs.crval[1] = phasecentre.dec.deg
# res.wcs.wcs.crpix[0] = float(nx // 2)
# res.wcs.wcs.crpix[1] = float(ny // 2)
store_image_in_c(py_outimg, res)
arl_create_test_image=collections.namedtuple("FFIX", "address")
arl_create_test_image.address=int(ff.cast("size_t", arl_create_test_image_ffi))
@ff.callback("void (*)(ARLConf *, double, int, char*, Image *)", onerror=handle_error)
def arl_create_low_test_image_from_gleam_ffi(lowconfig, cellsize, npixel, c_phasecentre, out_img):
py_outimg = cImage(out_img, new=True)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
phasecentre = load_phasecentre(c_phasecentre)
print("About to start create_low_test_image_from_gleam")
res = create_low_test_image_from_gleam(npixel=npixel, frequency=frequency,
channel_bandwidth=channel_bandwidth, cellsize=cellsize, flux_limit = 1.0, phasecentre=phasecentre, applybeam=True)
export_image_to_hdf5(res, '%s/gleam_model_res.hdf'%(results_dir))
nchan, npol, ny, nx = res.data.shape
# res.wcs.wcs.crval[0] = phasecentre.ra.deg
# res.wcs.wcs.crval[1] = phasecentre.dec.deg
# res.wcs.wcs.crpix[0] = float(nx // 2)
# res.wcs.wcs.crpix[1] = float(ny // 2)
export_image_to_hdf5(res, '%s/gleam_model_res1.hdf'%(results_dir))
store_image_in_c(py_outimg, res)
arl_create_low_test_image_from_gleam=collections.namedtuple("FFIX", "address")
arl_create_low_test_image_from_gleam.address=int(ff.cast("size_t", arl_create_low_test_image_from_gleam_ffi))
@ff.callback("void (*)(const ARLVis *, const Image *, ARLVis *)", onerror=handle_error)
def arl_predict_2d_ffi(vis_in, img, vis_out):
c_visin = cARLVis(vis_in)
py_visin = helper_create_visibility_object(c_visin)
c_img = cImage(img)
py_visin.phasecentre = load_phasecentre(vis_in.phasecentre)
res = predict_2d(py_visin, c_img)
vis_out.nvis = vis_in.nvis
vis_out.npol = vis_in.npol
c_visout = cARLVis(vis_out)
numpy.copyto(c_visout, res.data)
store_phasecentre(vis_out.phasecentre, res.phasecentre)
#arl_copy_visibility(py_visin, c_visout, False)
arl_predict_2d=collections.namedtuple("FFIX", "address")
arl_predict_2d.address=int(ff.cast("size_t", arl_predict_2d_ffi))
@ff.callback("void (*)(ARLConf *, const ARLVis *, const Image *, ARLVis *, ARLVis *, long long int *)", onerror=handle_error)
def arl_predict_function_ffi(lowconfig, vis_in, img, vis_out, blockvis_out, cindex_out):
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
cindex_size = lowconfig.nant*lowconfig.nant*lowconfig.nfreqs*lowconfig.ntimes
py_cindex = numpy.frombuffer(ff.buffer(cindex_out, 8*cindex_size), dtype='int', count=cindex_size)
c_visin = cARLBlockVis(vis_in, lowconfig.nant, lowconfig.nfreqs)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
py_visin = helper_create_blockvisibility_object(c_visin, frequency, channel_bandwidth, lowcore)
c_img = cImage(img)
py_visin.phasecentre = load_phasecentre(vis_in.phasecentre)
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
py_visin.polarisation_frame = PolarisationFrame(polframe)
# print("--------------------> predict_list_serial_workflow Phasecentre : ", py_visin.phasecentre.ra.deg, py_visin.phasecentre.dec.deg)
res = predict_list_serial_workflow(py_visin, c_img, vis_slices=51, context='wstack')
# print("--------------------> predict_list_serial_workflow sizeof(py_visin.data), sizeof(res.data)", sys.getsizeof(py_visin.data[:]), sys.getsizeof(res.data[:]))
# print("--------------------> predict_list_serial_workflow cindex", type(res.cindex), type(res.cindex[0]), len(res.cindex))
# print("--------------------> predict_list_serial_workflow sys.getsizeof(res.cindex)", sys.getsizeof(res.cindex))
# print("--------------------> predict_list_serial_workflow np.sum(predicted_vis.data): ", numpy.sum(res.data['vis']))
# print("--------------------> predict_list_serial_workflow predicted_vis.data: ", res.data)
# print("--------------------> predict_list_serial_workflow py_visin.data): ", py_visin.data)
# print("predict_list_serial_workflow np.sum(predicted_vis.data): ", numpy.sum(res.data['vis']))
vis_out.npol = vis_in.npol
c_visout = cARLVis(vis_out)
numpy.copyto(c_visout, res.data)
store_phasecentre(vis_out.phasecentre, res.phasecentre)
numpy.copyto(py_cindex, res.cindex)
py_blockvis_out = cARLBlockVis(blockvis_out, lowconfig.nant, lowconfig.nfreqs)
numpy.copyto(py_blockvis_out, res.blockvis.data)
store_phasecentre(blockvis_out.phasecentre, res.phasecentre)
arl_predict_function=collections.namedtuple("FFIX", "address")
arl_predict_function.address=int(ff.cast("size_t", arl_predict_function_ffi))
@ff.callback("void (*)(ARLConf *, ARLVis *, const Image *)", onerror=handle_error)
def arl_predict_function_blockvis_ffi(lowconfig, vis_in, img):
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
c_visin = cARLBlockVis(vis_in, lowconfig.nant, lowconfig.nfreqs)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
py_visin = helper_create_blockvisibility_object(c_visin, frequency, channel_bandwidth, lowcore)
c_img = cImage(img)
py_visin.phasecentre = load_phasecentre(vis_in.phasecentre)
log.info(qa_image(c_img, context='arl_predict_function'))
# export_image_to_fits(c_img, '%s/imaging-blockvis_model_in_predicted_function.fits'%(results_dir))
# export_blockvisibility_to_hdf5(py_visin, '%s/py_visin.hdf'%(results_dir))
# export_image_to_hdf5(c_img, '%s/gleam_model_c_img.hdf'%(results_dir))
py_blockvis = predict_list_serial_workflow(py_visin, c_img, vis_slices=51, context='wstack')
# export_blockvisibility_to_hdf5(py_blockvis, '%s/py_blockvis.hdf'%(results_dir))
# print(qa_visibility(py_blockvis, context='arl_predict_function_blockvis py_blockvis'))
# print("arl_predict_function_blockvis :", py_visin, py_blockvis)
numpy.copyto(c_visin, py_blockvis.data)
# store_phasecentre(vis_out.phasecentre, res.phasecentre)
# print("arl_predict_function_blockvis np.sum(py_blockvis.data): ", numpy.sum(py_blockvis.data['vis']))
# print("arl_predict_function_blockvis nchan npol nants ", py_blockvis.nchan, py_blockvis.npol, py_blockvis.nants)
# print("arl_predict_function_blockvis sum(uvw) ", numpy.sum(py_blockvis.uvw))
# print("arl_predict_function_blockvis sum(vis) ", numpy.sum(py_blockvis.vis))
# print("arl_predict_function_blockvis sum(weight) ", numpy.sum(py_blockvis.weight))
# print("arl_predict_function_blockvis time", py_blockvis.time, numpy.sum(py_blockvis.time))
# print("arl_predict_function_blockvis integration_time", py_blockvis.integration_time, numpy.sum(py_blockvis.integration_time))
# print("arl_predict_function_blockvis nvis, size", py_blockvis.nvis, py_blockvis.size())
arl_predict_function_blockvis=collections.namedtuple("FFIX", "address")
arl_predict_function_blockvis.address=int(ff.cast("size_t", arl_predict_function_blockvis_ffi))
@ff.callback("void (*)(ARLConf *, ARLVis *, const Image *, ARLVis *, long long int *, int)", onerror=handle_error)
def arl_predict_function_ical_ffi(lowconfig, vis_inout, img, blockvis_inout, cindex_inout, vis_slices):
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
cindex_size = lowconfig.nant*lowconfig.nant*lowconfig.nfreqs*lowconfig.ntimes
py_cindex = numpy.frombuffer(ff.buffer(cindex_inout, 8*cindex_size), dtype='int', count=cindex_size)
c_visinout = cARLVis(vis_inout)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
py_visinout = helper_create_visibility_object(c_visinout)
py_visinout.configuration = lowcore
py_visinout.phasecentre = load_phasecentre(vis_inout.phasecentre)
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
py_visinout.polarisation_frame = PolarisationFrame(polframe)
py_blockvis_inout = cARLBlockVis(blockvis_inout, lowconfig.nant, lowconfig.nfreqs)
py_blockvisinout = helper_create_blockvisibility_object(py_blockvis_inout, frequency, channel_bandwidth, lowcore)
py_visinout.blockvis = py_blockvisinout
py_visinout.cindex = py_cindex
c_img = cImage(img)
res = predict_list_serial_workflow(py_visinout, c_img, vis_slices=vis_slices, context='wstack',
timeslice='auto', algorithm='hogbom', niter=1000, fractional_threshold=0.1,
threshold=0.1, nmajor=5, gain=0.1, first_selfcal=1, global_solution=False)
# print("####################> arl_predict_function_ical: ", type(res))
numpy.copyto(c_visinout, res.data)
store_phasecentre(vis_inout.phasecentre, res.phasecentre)
numpy.copyto(py_cindex, res.cindex)
numpy.copyto(py_blockvis_inout, res.blockvis.data)
store_phasecentre(blockvis_inout.phasecentre, res.phasecentre)
# print("predict_function_ical np.sum(res.data): ", numpy.sum(res.data['vis']))
# print("predict_function_ical np.sum(res.blockvis.data): ", numpy.sum(res.blockvis.data['vis']))
arl_predict_function_ical=collections.namedtuple("FFIX", "address")
arl_predict_function_ical.address=int(ff.cast("size_t", arl_predict_function_ical_ffi))
@ff.callback("void (*)(ARLConf *, const ARLVis *, Image *, int, Image *)", onerror=handle_error)
def arl_invert_function_ffi(lowconfig, vis_in, img, vis_slices, img_dirty):
# Creating configuration
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
# Re-creating Visibility object
times = numpy.frombuffer(ff.buffer(lowconfig.times, 8*lowconfig.ntimes), dtype='f8', count=lowconfig.ntimes)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
c_visin = cARLVis(vis_in)
py_visin = helper_create_visibility_object(c_visin)
py_visin.phasecentre = load_phasecentre(vis_in.phasecentre)
py_visin.configuration = lowcore
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
py_visin.polarisation_frame = PolarisationFrame(polframe)
# Re-creating images
py_img = cImage(img)
py_img_dirty = cImage(img_dirty, new=True)
# Calling invert_finction()
# export_blockvisibility_to_hdf5(py_visin, '%s/py_visin_invert_function.hdf'%(results_dir))
# export_image_to_hdf5(py_img, '%s/model_invert_function.hdf'%(results_dir))
# print("arl_invert_function vis_slices: ", vis_slices)
dirty, sumwt = invert_list_serial_workflow(py_visin, py_img, vis_slices=vis_slices, dopsf=False, context='wstack')
nchan, npol, ny, nx = dirty.data.shape
# dirty.wcs.wcs.crval[0] = py_visin.phasecentre.ra.deg
# dirty.wcs.wcs.crval[1] = py_visin.phasecentre.dec.deg
# dirty.wcs.wcs.crpix[0] = float(nx // 2)
# dirty.wcs.wcs.crpix[1] = float(ny // 2)
# Copy Python dirty image into C image
store_image_in_c(py_img_dirty, dirty)
arl_invert_function=collections.namedtuple("FFIX", "address")
arl_invert_function.address=int(ff.cast("size_t", arl_invert_function_ffi))
@ff.callback("void (*)(ARLConf *, const ARLVis *, Image *, int, Image *)", onerror=handle_error)
def arl_invert_function_blockvis_ffi(lowconfig, vis_in, img, vis_slices, img_dirty):
# Creating configuration
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
# Re-creating Visibility object
times = numpy.frombuffer(ff.buffer(lowconfig.times, 8*lowconfig.ntimes), dtype='f8', count=lowconfig.ntimes)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
c_visin = cARLBlockVis(vis_in, lowconfig.nant, lowconfig.nfreqs)
py_visin = helper_create_blockvisibility_object(c_visin, frequency, channel_bandwidth, lowcore)
py_visin.phasecentre = load_phasecentre(vis_in.phasecentre)
py_visin.configuration = lowcore
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
py_visin.polarisation_frame = PolarisationFrame(polframe)
# Re-creating images
py_img = cImage(img)
py_img_dirty = cImage(img_dirty, new=True)
# Calling invert_finction()
# export_blockvisibility_to_hdf5(py_visin, '%s/py_visin_invert_function.hdf'%(results_dir))
# export_image_to_hdf5(py_img, '%s/model_invert_function.hdf'%(results_dir))
# print("arl_invert_function vis_slices: ", vis_slices)
dirty, sumwt = invert_list_serial_workflow(py_visin, py_img, vis_slices=vis_slices, dopsf=False, context='wstack')
nchan, npol, ny, nx = dirty.data.shape
# dirty.wcs.wcs.crval[0] = py_visin.phasecentre.ra.deg
# dirty.wcs.wcs.crval[1] = py_visin.phasecentre.dec.deg
# dirty.wcs.wcs.crpix[0] = float(nx // 2)
# dirty.wcs.wcs.crpix[1] = float(ny // 2)
# Copy Python dirty image into C image
store_image_in_c(py_img_dirty, dirty)
arl_invert_function_blockvis=collections.namedtuple("FFIX", "address")
arl_invert_function_blockvis.address=int(ff.cast("size_t", arl_invert_function_blockvis_ffi))
@ff.callback("void (*)(ARLConf *, const ARLVis *, Image *, int, Image *)", onerror=handle_error)
def arl_invert_function_ical_ffi(lowconfig, vis_in, img, vis_slices, img_dirty):
# Creating configuration
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
# Re-creating Visibility object
times = numpy.frombuffer(ff.buffer(lowconfig.times, 8*lowconfig.ntimes), dtype='f8', count=lowconfig.ntimes)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
c_visin = cARLVis(vis_in)
py_visin = helper_create_visibility_object(c_visin)
py_visin.phasecentre = load_phasecentre(vis_in.phasecentre)
py_visin.configuration = lowcore
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
py_visin.polarisation_frame = PolarisationFrame(polframe)
# Re-creating images
py_img = cImage(img)
py_img_dirty = cImage(img_dirty, new=True)
# Calling invert_finction()
dirty, sumwt = invert_list_serial_workflow(py_visin, py_img, vis_slices=vis_slices, context='wstack',
timeslice='auto', algorithm='hogbom', niter=1000, fractional_threshold=0.1,
threshold=0.1, nmajor=5, gain=0.1, first_selfcal=1, global_solution=False)
nchan, npol, ny, nx = dirty.data.shape
# dirty.wcs.wcs.crval[0] = py_visin.phasecentre.ra.deg
# dirty.wcs.wcs.crval[1] = py_visin.phasecentre.dec.deg
# dirty.wcs.wcs.crpix[0] = float(nx // 2)
# dirty.wcs.wcs.crpix[1] = float(ny // 2)
# Copy Python dirty image into C image
store_image_in_c(py_img_dirty, dirty)
log.info("Maximum in residual image is %.6f" % (numpy.max(numpy.abs(dirty.data))))
arl_invert_function_ical=collections.namedtuple("FFIX", "address")
arl_invert_function_ical.address=int(ff.cast("size_t", arl_invert_function_ical_ffi))
@ff.callback("void (*)(ARLConf *, const ARLVis *, Image *, int, Image *)", onerror=handle_error)
def arl_invert_function_psf_ffi(lowconfig, vis_in, img, vis_slices, img_psf):
# Creating configuration
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
# Re-creating Visibility object
times = numpy.frombuffer(ff.buffer(lowconfig.times, 8*lowconfig.ntimes), dtype='f8', count=lowconfig.ntimes)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
c_visin = cARLVis(vis_in)
py_visin = helper_create_visibility_object(c_visin)
py_visin.phasecentre = load_phasecentre(vis_in.phasecentre)
py_visin.configuration = lowcore
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
py_visin.polarisation_frame = PolarisationFrame(polframe)
# Re-creating images
py_img = cImage(img)
py_img_psf = cImage(img_psf, new=True)
# Calling invert_finction()
psf, sumwt = invert_list_serial_workflow(py_visin, py_img, vis_slices=vis_slices, dopsf=True, context='wstack',
timeslice='auto', algorithm='hogbom', niter=1000, fractional_threshold=0.1,
threshold=0.1, nmajor=5, gain=0.1, first_selfcal=1, global_solution=False)
nchan, npol, ny, nx = psf.data.shape
# psf.wcs.wcs.crval[0] = py_visin.phasecentre.ra.deg
# psf.wcs.wcs.crval[1] = py_visin.phasecentre.dec.deg
# psf.wcs.wcs.crpix[0] = float(nx // 2)
# psf.wcs.wcs.crpix[1] = float(ny // 2)
# Copy Python dirty image into C image
store_image_in_c(py_img_psf, psf)
arl_invert_function_psf=collections.namedtuple("FFIX", "address")
arl_invert_function_psf.address=int(ff.cast("size_t", arl_invert_function_psf_ffi))
@ff.callback("void (*)(ARLConf *, const ARLVis *, Image *, int, Image *, Image *, Image *)", onerror=handle_error)
def arl_ical_ffi(lowconfig, blockvis_in, img_model, vis_slices, img_deconvolved, img_residual, img_restored):
# Creating configuration
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
# Re-creating BlockVisibility object
times = numpy.frombuffer(ff.buffer(lowconfig.times, 8*lowconfig.ntimes), dtype='f8', count=lowconfig.ntimes)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
c_blockvisin = cARLBlockVis(blockvis_in, lowconfig.nant, lowconfig.nfreqs)
py_blockvisin = helper_create_blockvisibility_object(c_blockvisin, frequency, channel_bandwidth, lowcore)
py_blockvisin.phasecentre = load_phasecentre(blockvis_in.phasecentre)
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
py_blockvisin.polarisation_frame = PolarisationFrame(polframe)
# Re-creating images
py_model = cImage(img_model)
py_img_deconvolved = cImage(img_deconvolved, new=True)
py_img_residual = cImage(img_residual, new=True)
py_img_restored = cImage(img_restored, new=True)
# Callinc ical_list_serial_workflow()
deconvolved, residual, restored = ical_list_serial_workflow(block_vis=py_blockvisin, model=py_model, vis_slices=vis_slices,
timeslice='auto',
algorithm='hogbom', niter=1000, fractional_threshold=0.1, threshold=0.1,
context='wstack', nmajor=5, gain=0.1, first_selfcal=1,
global_solution=False)
# Preparing deconvolved
nchan, npol, ny, nx = deconvolved.data.shape
# deconvolved.wcs.wcs.crval[0] = py_blockvisin.phasecentre.ra.deg
# deconvolved.wcs.wcs.crval[1] = py_blockvisin.phasecentre.dec.deg
# deconvolved.wcs.wcs.crpix[0] = float(nx // 2)
# deconvolved.wcs.wcs.crpix[1] = float(ny // 2)
store_image_in_c(py_img_deconvolved, deconvolved)
# Preparing residual
nchan, npol, ny, nx = residual.data.shape
# residual.wcs.wcs.crval[0] = py_blockvisin.phasecentre.ra.deg
# residual.wcs.wcs.crval[1] = py_blockvisin.phasecentre.dec.deg
# residual.wcs.wcs.crpix[0] = float(nx // 2)
# residual.wcs.wcs.crpix[1] = float(ny // 2)
store_image_in_c(py_img_residual, residual)
# Preparing restored
nchan, npol, ny, nx = restored.data.shape
# restored.wcs.wcs.crval[0] = py_blockvisin.phasecentre.ra.deg
# restored.wcs.wcs.crval[1] = py_blockvisin.phasecentre.dec.deg
# restored.wcs.wcs.crpix[0] = float(nx // 2)
# restored.wcs.wcs.crpix[1] = float(ny // 2)
store_image_in_c(py_img_restored, restored)
arl_ical=collections.namedtuple("FFIX", "address")
arl_ical.address=int(ff.cast("size_t", arl_ical_ffi))
@ff.callback("void (*)(const ARLVis *, const Image *, bool dopsf, Image *, double *)")
def arl_invert_2d_ffi(invis, in_image, dopsf, out_image, sumwt):
py_visin = helper_create_visibility_object(cARLVis(invis))
c_in_img = cImage(in_image)
c_out_img = cImage(out_image, new=True)
py_visin.phasecentre = load_phasecentre(invis.phasecentre)
if dopsf:
out, sumwt = invert_2d(py_visin, c_in_img, dopsf=True)
else:
out, sumwt = invert_2d(py_visin, c_in_img)
store_image_in_c_2(c_out_img, out)
arl_invert_2d=collections.namedtuple("FFIX", "address")
arl_invert_2d.address=int(ff.cast("size_t", arl_invert_2d_ffi))
@ff.callback("void (*)(const ARLVis *, Image *)", onerror=handle_error)
def arl_create_image_from_visibility_ffi(vis_in, img_in):
c_vis = cARLVis(vis_in)
c_img = cImage(img_in, new=True)
# We need a proper Visibility object - not this, and not a cARLVis
# This is temporary - just so we have some data to pass to
# the create_... routine
tvis = helper_create_visibility_object(c_vis)
tvis.phasecentre = load_phasecentre(vis_in.phasecentre)
# Default args for now
image = create_image_from_visibility(tvis, cellsize=0.001, npixel=256)
#numpy.copyto(c_img.data, image.data)
# Pickle WCS and polframe, until better way is found to handle these data
# structures
#store_image_pickles(c_img, image)
store_image_in_c(c_img, image)
arl_create_image_from_visibility=collections.namedtuple("FFIX", "address")
arl_create_image_from_visibility.address=int(ff.cast("size_t",
arl_create_image_from_visibility_ffi))
@ff.callback("void (*)(ARLConf *, const ARLVis *, double, int, char*, Image *)", onerror=handle_error)
def arl_create_image_from_blockvisibility_ffi(lowconfig, blockvis_in, cellsize, npixel, c_phasecentre, img_out):
# Creating configuration
lowcore_name = str(ff.string(lowconfig.confname), 'utf-8')
lowcore = create_named_configuration(lowcore_name, rmax=lowconfig.rmax)
# Re-creating BlockVisibility object
c_blockvisin = cARLBlockVis(blockvis_in, lowconfig.nant, lowconfig.nfreqs)
frequency = numpy.frombuffer(ff.buffer(lowconfig.freqs, 8*lowconfig.nfreqs), dtype='f8', count=lowconfig.nfreqs)
channel_bandwidth = numpy.frombuffer(ff.buffer(lowconfig.channel_bandwidth, 8*lowconfig.nchanwidth), dtype='f8', count=lowconfig.nchanwidth)
py_blockvisin = helper_create_blockvisibility_object(c_blockvisin, frequency, channel_bandwidth, lowcore)
# py_blockvisin.phasecentre = load_phasecentre(blockvis_in.phasecentre)
# Copying phasecentre and other metadata
phasecentre = load_phasecentre(c_phasecentre)
py_blockvisin.phasecentre = phasecentre
polframe = str(ff.string(lowconfig.polframe), 'utf-8')
py_blockvisin.polarisation_frame = PolarisationFrame(polframe)
phasecentre1 = SkyCoord(ra=lowconfig.pc_ra * u.deg, dec=lowconfig.pc_dec*u.deg, frame='icrs',
equinox='J2000')
# Re-creating Image object
py_outimg = cImage(img_out, new=True)
# Construct a model from py_blockvisin
res = create_image_from_visibility(py_blockvisin, npixel=npixel, frequency=[numpy.average(frequency)], nchan=1,
channel_bandwidth=[numpy.sum(channel_bandwidth)], cellsize=cellsize, phasecentre=phasecentre1)
#numpy.copyto(c_img.data, image.data)
# Pickle WCS and polframe, until better way is found to handle these data
# structures
#store_image_pickles(c_img, image)
nchan, npol, ny, nx = res.data.shape
# res.wcs.wcs.crval[0] = phasecentre1.ra.deg
# res.wcs.wcs.crval[1] = phasecentre1.dec.deg
# res.wcs.wcs.crpix[0] = float(nx // 2)
# res.wcs.wcs.crpix[1] = float(ny // 2)
store_image_in_c(py_outimg, res)
arl_create_image_from_blockvisibility=collections.namedtuple("FFIX", "address")
arl_create_image_from_blockvisibility.address=int(ff.cast("size_t",
arl_create_image_from_blockvisibility_ffi))
@ff.callback("void (*)(Image *, Image *, Image *, Image *)", onerror=handle_error)
def arl_deconvolve_cube_ffi(dirty, psf, restored, residual):
c_dirty = cImage(dirty)
c_psf = cImage(psf)
c_residual = cImage(residual, new=True)
c_restored = cImage(restored, new=True)
py_restored, py_residual = deconvolve_cube(c_dirty, c_psf,
niter=1000,threshold=0.001, fracthresh=0.01, window_shape='quarter',
gain=0.7, scales=[0,3,10,30])
store_image_in_c(c_restored,py_restored)
store_image_in_c(c_residual,py_residual)
arl_deconvolve_cube=collections.namedtuple("FFIX", "address")
arl_deconvolve_cube.address=int(ff.cast("size_t", arl_deconvolve_cube_ffi))
@ff.callback("void (*)(Image *, Image *, Image *, Image *)", onerror=handle_error)
def arl_deconvolve_cube_ical_ffi(dirty, psf, restored, residual):
c_dirty = cImage(dirty)
c_psf = cImage(psf)
c_residual = cImage(residual, new=True)
c_restored = cImage(restored, new=True)
py_restored, py_residual = deconvolve_cube(c_dirty, c_psf,
timeslice='auto', algorithm='hogbom', niter=1000, fractional_threshold=0.1,
threshold=0.1, nmajor=5, gain=0.1, first_selfcal=1, global_solution=False)
store_image_in_c(c_restored,py_restored)
store_image_in_c(c_residual,py_residual)
arl_deconvolve_cube_ical=collections.namedtuple("FFIX", "address")
arl_deconvolve_cube_ical.address=int(ff.cast("size_t", arl_deconvolve_cube_ical_ffi))
@ff.callback("void (*)(Image *, Image *, Image*, Image*)", onerror=handle_error)
def arl_restore_cube_ffi(model, psf, residual, restored):
# Cast C Image structs to Python objects
c_model = cImage(model)
c_psf = cImage(psf)
if residual:
c_residual = cImage(residual)
else:
c_residual = None
c_restored = cImage(restored, new=True)
# Calculate
py_restored = restore_cube(c_model, c_psf, c_residual)
# Copy Python result to C result struct
store_image_in_c(c_restored,py_restored)
arl_restore_cube=collections.namedtuple("FFIX", "address")
arl_restore_cube.address=int(ff.cast("size_t", arl_restore_cube_ffi))
@ff.callback("void (*)(Image *, Image *, Image*, Image*)", onerror=handle_error)
def arl_restore_cube_ical_ffi(model, psf, residual, restored):
# Cast C Image structs to Python objects
c_model = cImage(model)
c_psf = cImage(psf)
if residual:
c_residual = cImage(residual)
else:
c_residual = None
c_restored = cImage(restored, new=True)
# Calculate
py_restored = restore_cube(c_model, c_psf, c_residual,
timeslice='auto', algorithm='hogbom', niter=1000, fractional_threshold=0.1,
threshold=0.1, nmajor=5, gain=0.1, first_selfcal=1, global_solution=False)
# Copy Python result to C result struct
store_image_in_c(c_restored,py_restored)
arl_restore_cube_ical=collections.namedtuple("FFIX", "address")
arl_restore_cube_ical.address=int(ff.cast("size_t", arl_restore_cube_ical_ffi))
| {
"repo_name": "SKA-ScienceDataProcessor/algorithm-reference-library",
"path": "deprecated_code/ffiwrappers/src/arlwrap.py",
"copies": "1",
"size": "64539",
"license": "apache-2.0",
"hash": 5170159498931707000,
"line_mean": 46.9131403118,
"line_max": 165,
"alpha_frac": 0.7161251336,
"autogenerated": false,
"ratio": 2.9315920962979787,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9106009326528568,
"avg_score": 0.008341580673882151,
"num_lines": 1347
} |
import cffi
import numpy
from data_models.memory_data_models import Image, Visibility, BlockVisibility, GainTable
import pickle
ff = cffi.FFI()
def ARLDataVisSize(nvis, npol):
return (80+32*int(npol))*int(nvis)
def cARLVis(visin):
"""
Convert a const ARLVis * into the ARL Visiblity structure
"""
npol=visin.npol
nvis=visin.nvis
#print (ARLDataVisSize(nvis, npol))
desc = [('index', 'i8'),
('uvw', 'f8', (3,)),
('time', 'f8'),
('frequency', 'f8'),
('channel_bandwidth', 'f8'),
('integration_time', 'f8'),
('antenna1', 'i8'),
('antenna2', 'i8'),
('vis', 'c16', (npol,)),
('weight', 'f8', (npol,)),
('imaging_weight', 'f8', (npol,))]
r=numpy.frombuffer(ff.buffer(visin.data,
ARLDataVisSize(nvis, npol)),
dtype=desc,
count=nvis)
return r
def ARLBlockDataVisSize(ntimes, nants, nchan, npol):
return (24+24*int(nants*nants) + 24*int(nants*nants)*int(nchan)*int(npol))*int(ntimes)
def cARLBlockVis(visin, nants, nchan):
"""
Convert a const ARLVis * into the ARL BlockVisiblity structure
"""
npol=visin.npol
ntimes=visin.nvis
#print (ARLDataVisSize(nvis, npol))
desc = [('index', 'i8'),
('uvw', 'f8', (nants, nants, 3)),
('time', 'f8'),
('integration_time', 'f8'),
('vis', 'c16', (nants, nants, nchan, npol)),
('weight', 'f8', (nants, nants, nchan, npol))]
r=numpy.frombuffer(ff.buffer(visin.data,
ARLBlockDataVisSize(ntimes, nants, nchan, npol)),
dtype=desc,
count=ntimes)
return r
def ARLDataGTSize(ntimes, nants, nchan, nrec):
return (8 + 8*nchan*nrec*nrec + 3*8*nants*nchan*nrec*nrec + 8)*ntimes
def cARLGt(gtin, nants, nchan, nrec):
"""
Convert a const ARLGt * into the ARL GainTable structure
"""
ntimes=gtin.nrows
desc = [('gain', 'c16', (nants, nchan, nrec, nrec)),
('weight', 'f8', (nants, nchan, nrec, nrec)),
('residual', 'f8', (nchan, nrec, nrec)),
('time', 'f8'),
('interval', 'f8')]
r=numpy.frombuffer(ff.buffer(gtin.data,
ARLDataGTSize(ntimes, nants, nchan, nrec)),
dtype=desc,
count=ntimes)
return r
def store_pickle(c_dest, py_src, raw_c_ptr=False):
src_pickle = pickle.dumps(py_src)
src_buf = numpy.frombuffer(src_pickle, dtype='b',
count=len(src_pickle))
# Create ndarray if necessary
if (raw_c_ptr):
c_dest = numpy.frombuffer(ff.buffer(c_dest, len(src_pickle)),
dtype='b', count=len(src_pickle))
numpy.copyto(c_dest, src_buf)
def load_pickle(c_ptr, size):
return pickle.loads(numpy.frombuffer(ff.buffer(c_ptr, size),
dtype='b',
count=size))
def store_image_pickles(c_img, py_img):
store_pickle(c_img.wcs, py_img.wcs)
store_pickle(c_img.polarisation_frame, py_img.polarisation_frame)
# Turns ARLVis struct into Visibility object
def helper_create_visibility_object(c_vis):
# This may be incorrect
# especially the data field...
tvis= Visibility(
data=c_vis,
frequency=c_vis['frequency'],
channel_bandwidth=c_vis['channel_bandwidth'],
integration_time=c_vis['integration_time'],
antenna1=c_vis['antenna1'],
antenna2=c_vis['antenna2'],
weight=c_vis['weight'],
imaging_weight=c_vis['imaging_weight'],
uvw=c_vis['uvw'],
time=c_vis['time']
)
return tvis
# Turns ARLVis struct into BlockVisibility object
def helper_create_blockvisibility_object(c_vis, freqs, chan_b, config):
# This may be incorrect
# especially the data field...
tvis= BlockVisibility(
data=c_vis,
frequency = freqs,
channel_bandwidth = chan_b,
configuration = config,
integration_time=c_vis['integration_time'],
weight=c_vis['weight'],
uvw=c_vis['uvw'],
time=c_vis['time']
)
return tvis
# Turns ARLGt struct into GainTable object
def helper_create_gaintable_object(c_gt, freqs, recframe):
tgt= GainTable(
data=None,
frequency = freqs,
gain=c_gt['gain'],
weight=c_gt['weight'],
residual=c_gt['residual'],
time=c_gt['time'],
interval=c_gt['interval'],
receptor_frame=recframe
)
# print(tgt.__dict__)
return tgt
def cImage(image_in, new=False):
"Convert an Image* into ARL Image structure"
new_image = Image()
size = image_in.size
data_shape = tuple(image_in.data_shape)
new_image.data = numpy.frombuffer(ff.buffer(image_in.data,size*8),
dtype='f8',
count=size)
# frombuffer only does 1D arrays..
new_image.data = new_image.data.reshape(data_shape)
# New images don't have pickles yet
if new:
new_image.wcs = numpy.frombuffer(ff.buffer(image_in.wcs,
2996),
dtype='b',
count=2996)
new_image.polarisation_frame = numpy.frombuffer(ff.buffer(
image_in.polarisation_frame, 117),
dtype='b',
count=117)
else:
new_image.wcs = pickle.loads(ff.buffer(image_in.wcs, 2996))
new_image.polarisation_frame = pickle.loads(ff.buffer(image_in.polarisation_frame,117))
return new_image
# Write cImage data into C structs
def store_image_in_c(img_to, img_from):
numpy.copyto(img_to.data, img_from.data)
store_image_pickles(img_to, img_from)
# Phasecentres are too Pythonic to handle right now, so we pickle them
def store_phasecentre(c_phasecentre, phasecentre):
store_pickle(c_phasecentre, phasecentre, raw_c_ptr=True)
def load_phasecentre(c_phasecentre):
return load_pickle(c_phasecentre, 4999)
def store_image_in_c_2(img_to, img_from):
numpy.copyto(img_to.data, img_from.data)
store_image_pickles(img_to, img_from)
| {
"repo_name": "SKA-ScienceDataProcessor/algorithm-reference-library",
"path": "deprecated_code/ffiwrappers/src/arlwrap_support.py",
"copies": "1",
"size": "6364",
"license": "apache-2.0",
"hash": -703055979540557400,
"line_mean": 30.3497536946,
"line_max": 95,
"alpha_frac": 0.5691389063,
"autogenerated": false,
"ratio": 3.197989949748744,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9188585879665159,
"avg_score": 0.015708595276717214,
"num_lines": 203
} |
__author__ = 'boris'
from scipy.stats.mstats import winsorize
import scipy.stats as stats
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from collections import defaultdict
import numpy
import math
import mod_lib
import mod_utils
import operator
import os
import uniform_colormaps
from statsmodels.nonparametric.smoothers_lowess import lowess
from matplotlib import rc
plt.rcParams['pdf.fonttype'] = 42 #leaves most text as actual text in PDFs, not outlines
#plt.rcParams["font.family"] = "sans-serif"
rc('font',**{'family':'sans-serif','sans-serif':['Bitstream Vera Sans']})
#rc('text', usetex=True)
def plot_mutated_nts_pie(libraries, out_prefix, subtract_background=False, subtract_control=False, exclude_constitutive=False):
#Makes an array of pie charts, 1 per library
if subtract_background:
#if subtracting background, need to only look at those which have a defined control
libraries = [library for library in libraries if (library.lib_settings.sample_name in
library.experiment_settings.get_property('experimentals')) or (library.lib_settings.sample_name in
library.experiment_settings.get_property('with_mod_controls'))]
elif subtract_control:
#if subtracting background, need to only look at those which have a defined control
libraries = [library for library in libraries if library.lib_settings.sample_name in
library.experiment_settings.get_property('experimentals')]
num_subplots = len(libraries)
num_plots_wide = math.ceil(math.sqrt(num_subplots))
num_plots_high = num_plots_wide
fig = plt.figure(figsize=(4*num_plots_wide, 4*num_plots_high))
fig.subplots_adjust(wspace=0.4, hspace=0.4)
plot_index =1
for library in libraries:
plot = fig.add_subplot(num_plots_high, num_plots_wide, plot_index)
mutated_nts_count = library.count_mutation_rates_by_nucleotide(subtract_background=subtract_background, subtract_control=subtract_control,
exclude_constitutive=exclude_constitutive)
labels = sorted(mutated_nts_count.keys())
sizes = numpy.array([mutated_nts_count[nt] for nt in labels])
total = float(sum(sizes))
sizes = sizes/total
merged_labels = ['%s %.3f' % (labels[i], sizes[i]) for i in range(len(sizes))]
plot.pie(sizes, labels = merged_labels, colors = mod_utils.rainbow)
plot.set_title(library.lib_settings.sample_name)
plot_index += 1
if subtract_background:
plt.suptitle('background-subtracted mutation rate fractions')
if subtract_control:
plt.suptitle('control-subtracted mutation rate fractions')
else:
plt.suptitle('mutation rate fractions')
plt.savefig(out_prefix + '.pdf', transparent='True', format='pdf')
plt.clf()
def plot_rt_stop_pie(libraries, out_prefix, subtract_background=False, subtract_control=False, exclude_constitutive=False):
#Makes an array of pie charts, 1 per library
if subtract_background:
#if subtracting background, need to only look at those which have a defined control
libraries = [library for library in libraries if (library.lib_settings.sample_name in
library.experiment_settings.get_property('experimentals')) or (library.lib_settings.sample_name in
library.experiment_settings.get_property('with_mod_controls'))]
num_subplots = len(libraries)
num_plots_wide = math.ceil(math.sqrt(num_subplots))
num_plots_high = num_plots_wide
fig = plt.figure(figsize=(4*num_plots_wide, 4*num_plots_high))
fig.subplots_adjust(wspace=0.4, hspace=0.4)
plot_index =1
for library in libraries:
plot = fig.add_subplot(num_plots_high, num_plots_wide, plot_index)
rt_stop_count = library.count_rt_stop_rpm_by_nucleotide(subtract_background=subtract_background, subtract_control=subtract_control,
exclude_constitutive=exclude_constitutive)
labels = sorted(rt_stop_count.keys())
sizes = numpy.array([rt_stop_count[nt] for nt in labels])
total = float(sum(sizes))
sizes = sizes/total
merged_labels = ['%s %.3f' % (labels[i], sizes[i]) for i in range(len(sizes))]
plot.pie(sizes, labels = merged_labels, colors = mod_utils.rainbow)
plot.set_title(library.lib_settings.sample_name)
plot_index += 1
if subtract_background:
plt.suptitle('background-subtracted fraction of RT stops')
else:
plt.suptitle('fraction of RT stops')
plt.savefig(out_prefix + '.pdf', transparent='True', format='pdf')
plt.clf()
def plot_mutation_breakdown_pie(libraries, out_prefix, exclude_constitutive=False):
#Makes an array of pie charts, 4 pers library, with types of mutations for each nt
num_subplots = len(libraries)*4
num_plots_wide = 4
num_plots_high = len(libraries)
fig = plt.figure(figsize=(16, 4*num_plots_high))
fig.subplots_adjust(wspace=0.4, hspace=0.4)
plot_index =1
for library in libraries:
mutated_nts_count = library.count_mutation_types_by_nucleotide(exclude_constitutive=exclude_constitutive)
for nt in 'ATCG':
plot = fig.add_subplot(num_plots_high, num_plots_wide, plot_index)
sorted_muts = sorted(mutated_nts_count[nt].items(), key=operator.itemgetter(1), reverse=True)
labels = [pair[0] for pair in sorted_muts[:4]]
others = [pair[0] for pair in sorted_muts[4:]]
sizes = [mutated_nts_count[nt][mut_type] for mut_type in labels]
labels.append('other')
other_sum = sum([mutated_nts_count[nt][mut_type] for mut_type in others])
sizes.append(other_sum)
sizes = numpy.array(sizes)
total = float(sum(sizes))
sizes = sizes/total
merged_labels = ['%s %.3f' % (labels[i], sizes[i]) for i in range(len(sizes))]
plot.pie(sizes, labels = merged_labels, colors = mod_utils.rainbow)
plot.set_title(library.lib_settings.sample_name)
plot_index += 1
plt.suptitle('mutation rate type fractions')
plt.savefig(out_prefix + '.pdf', transparent='True', format='pdf')
plt.clf()
def plot_mutation_rate_cdfs(libraries, out_prefix, nucleotides_to_count='ATCG', exclude_constitutive=False):
#Makes 2 CDF plots. One of all libraries, showing the coverage-normalized mutation rates
# and one showing background-subtracted mutation rates
fig = plt.figure(figsize=(16, 16))
plots = []
plot = fig.add_subplot(221)
plots.append(plot)
colormap = plt.get_cmap('nipy_spectral')
colorindex = 0
for library in libraries:
all_mutation_rates = [val for val in
library.list_mutation_rates(subtract_background=False, subtract_control=False,
nucleotides_to_count=nucleotides_to_count, exclude_constitutive=exclude_constitutive)]
plot.hist(all_mutation_rates, 10000, normed=1, cumulative=True, histtype='step', color=colormap(colorindex/float(len(libraries))),
label=library.lib_settings.sample_name, lw=2)
colorindex += 1
plot.set_xlabel("mutation rate")
plot.set_title('raw mutation rates')
lg=plt.legend(loc=4,prop={'size':6}, labelspacing=0.2)
lg.draw_frame(False)
plot.set_xlim(-0.001, 0.02)
plot = fig.add_subplot(222)
plots.append(plot)
colorindex = 0
libraries_to_plot = [library for library in libraries if library.lib_settings.sample_name in
library.experiment_settings.get_property('experimentals')]
for library in libraries_to_plot:
all_mutation_rates = [val for val in
library.list_mutation_rates(subtract_background=True, subtract_control=False,
nucleotides_to_count=nucleotides_to_count, exclude_constitutive=exclude_constitutive)]
plot.hist(all_mutation_rates, 10000, normed=1, cumulative=True, histtype='step', color=colormap(colorindex/float(len(libraries))),
label=library.lib_settings.sample_name, lw=2)
colorindex += 1
plot.set_xlabel("background-subtracted mutation rate")
plot.set_title('normalized mutation rates')
lg=plt.legend(loc=4,prop={'size':6}, labelspacing=0.2)
lg.draw_frame(False)
plot.set_xlim(-0.001, 0.02)
plot = fig.add_subplot(223)
plots.append(plot)
colormap = plt.get_cmap('nipy_spectral')
colorindex = 0
for library in libraries:
all_mutation_rates = [math.log(val, 10) for val in
library.list_mutation_rates(subtract_background=False, subtract_control=False,
nucleotides_to_count=nucleotides_to_count, exclude_constitutive=exclude_constitutive) if val>0]
plot.hist(all_mutation_rates, 10000, normed=1, cumulative=True, histtype='step', color=colormap(colorindex/float(len(libraries))),
label=library.lib_settings.sample_name, lw=2)
colorindex += 1
plot.set_xlabel("log10 mutation rate")
plot.set_title('raw mutation rates')
lg=plt.legend(loc=2,prop={'size':6}, labelspacing=0.2)
lg.draw_frame(False)
plot.set_xlim(-5, -1)
plot = fig.add_subplot(224)
plots.append(plot)
colorindex = 0
libraries_to_plot = [library for library in libraries if library.lib_settings.sample_name in
library.experiment_settings.get_property('experimentals')]
for library in libraries_to_plot:
all_mutation_rates = [math.log(val, 10) for val in
library.list_mutation_rates(subtract_background=True, subtract_control=False,
nucleotides_to_count=nucleotides_to_count, exclude_constitutive=exclude_constitutive) if val>0]
plot.hist(all_mutation_rates, 10000, normed=1, cumulative=True, histtype='step', color=colormap(colorindex/float(len(libraries))),
label=library.lib_settings.sample_name, lw=2)
colorindex += 1
plot.set_xlabel("background-subtracted log10 mutation rate")
plot.set_title('normalized mutation rates')
lg=plt.legend(loc=2,prop={'size':6}, labelspacing=0.2)
lg.draw_frame(False)
plot.set_xlim(-5, -1)
for plot in plots:
plot.set_ylabel("cumulative fraction of %s nucleotides" % (nucleotides_to_count))
plot.set_ylim(0, 1)
plt.tight_layout()
plt.savefig(out_prefix + '.pdf', transparent='True', format='pdf')
plt.clf()
def plot_rt_stop_cdfs(libraries, out_prefix, nucleotides_to_count='ATCG', exclude_constitutive=False):
#Makes 2 CDF plots. One of all libraries, showing the coverage-normalized mutation rates
# and one showing background-subtracted mutation rates
fig = plt.figure(figsize=(16, 16))
plots = []
plot = fig.add_subplot(221)
plots.append(plot)
colormap = plt.get_cmap('nipy_spectral')
colorindex = 0
for library in libraries:
all_mutation_rates = [val for val in
library.list_rt_stop_rpms(subtract_background=False, subtract_control=False,
nucleotides_to_count=nucleotides_to_count, exclude_constitutive=exclude_constitutive)]
plot.hist(all_mutation_rates, 10000, normed=1, cumulative=True, histtype='step', color=colormap(colorindex/float(len(libraries))),
label=library.lib_settings.sample_name, lw=2)
colorindex += 1
plot.set_xlabel("RT stop RPMs")
#plot.set_title('raw mutation rates')
lg=plt.legend(loc=4,prop={'size':6}, labelspacing=0.2)
lg.draw_frame(False)
plot.set_xlim(0, 10000)
plot = fig.add_subplot(222)
plots.append(plot)
colorindex = 0
libraries_to_plot = [library for library in libraries if library.lib_settings.sample_name in
library.experiment_settings.get_property('experimentals')]
for library in libraries_to_plot:
all_mutation_rates = [val for val in
library.list_rt_stop_rpms(subtract_background=True, subtract_control=False,
nucleotides_to_count=nucleotides_to_count, exclude_constitutive=exclude_constitutive)]
plot.hist(all_mutation_rates, 10000, normed=1, cumulative=True, histtype='step', color=colormap(colorindex/float(len(libraries))),
label=library.lib_settings.sample_name, lw=2)
colorindex += 1
plot.set_xlabel("background-subtracted RT-stop RPMs")
#plot.set_title('normalized mutation rates')
lg=plt.legend(loc=4,prop={'size':6}, labelspacing=0.2)
lg.draw_frame(False)
plot.set_xlim(0, 10000)
plot = fig.add_subplot(223)
plots.append(plot)
colormap = plt.get_cmap('nipy_spectral')
colorindex = 0
for library in libraries:
all_mutation_rates = [math.log(val, 10) for val in
library.list_rt_stop_rpms(subtract_background=False, subtract_control=False,
nucleotides_to_count=nucleotides_to_count, exclude_constitutive=exclude_constitutive) if val>0]
plot.hist(all_mutation_rates, 10000, normed=1, cumulative=True, histtype='step', color=colormap(colorindex/float(len(libraries))),
label=library.lib_settings.sample_name, lw=2)
colorindex += 1
plot.set_xlabel("log10 RT stop RPMs")
#plot.set_title('raw mutation rates')
lg=plt.legend(loc=2,prop={'size':6}, labelspacing=0.2)
lg.draw_frame(False)
plot.set_xlim(0, 5)
plot = fig.add_subplot(224)
plots.append(plot)
colorindex = 0
libraries_to_plot = [library for library in libraries if library.lib_settings.sample_name in
library.experiment_settings.get_property('experimentals')]
for library in libraries_to_plot:
all_mutation_rates = [math.log(val, 10) for val in
library.list_rt_stop_rpms(subtract_background=True, subtract_control=False,
nucleotides_to_count=nucleotides_to_count, exclude_constitutive=exclude_constitutive) if val>0]
plot.hist(all_mutation_rates, 10000, normed=1, cumulative=True, histtype='step', color=colormap(colorindex/float(len(libraries))),
label=library.lib_settings.sample_name, lw=2)
colorindex += 1
plot.set_xlabel("background-subtracted log10 RT stop RPMs")
#plot.set_title('normalized mutation rates')
lg=plt.legend(loc=2,prop={'size':6}, labelspacing=0.2)
lg.draw_frame(False)
plot.set_xlim(0, 5)
for plot in plots:
plot.set_ylabel("cumulative fraction of %s nucleotides" % (nucleotides_to_count))
plot.set_ylim(0, 1)
plt.tight_layout()
plt.savefig(out_prefix + '.pdf', transparent='True', format='pdf')
plt.clf()
def plot_mutation_rate_violins(libraries, out_prefix, nucleotides_to_count='ATCG', exclude_constitutive=False):
#Makes violin plots of raw mutation rates
data = []
labels = []
for library in libraries:
labels.append(library.lib_settings.sample_name)
data.append([math.log10(val) for val in library.list_mutation_rates(subtract_background=False, subtract_control=False,
nucleotides_to_count=nucleotides_to_count,
exclude_constitutive=exclude_constitutive) if val>0])
colormap = uniform_colormaps.viridis
fig = plt.figure(figsize=(5,8))
ax1 = fig.add_subplot(111)
# Hide the grid behind plot objects
ax1.yaxis.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.5)
ax1.set_axisbelow(True)
#ax1.set_xlabel(ylabel)
plt.subplots_adjust(left=0.1, right=0.95, top=0.9, bottom=0.25)
pos = range(1,len(libraries)+1) # starts at 1 to play nice with boxplot
dist = max(pos)-min(pos)
w = min(0.15*max(dist,1.0),0.5)
for library,p in zip(libraries,pos):
d = [math.log10(val) for val in library.list_mutation_rates(subtract_background=False, subtract_control=False,
nucleotides_to_count=nucleotides_to_count,
exclude_constitutive=exclude_constitutive) if val>0]
k = stats.gaussian_kde(d) #calculates the kernel density
m = k.dataset.min() #lower bound of violin
M = k.dataset.max() #upper bound of violin
x = numpy.arange(m,M,(M-m)/100.) # support for violin
v = k.evaluate(x) #violin profile (density curve)
v = v/v.max()*w #scaling the violin to the available space
plt.fill_betweenx(x,p,v+p,facecolor=colormap((p-1)/float(len(libraries))),alpha=0.3)
plt.fill_betweenx(x,p,-v+p,facecolor=colormap((p-1)/float(len(libraries))),alpha=0.3)
if True:
bplot = plt.boxplot(data,notch=1)
plt.setp(bplot['boxes'], color='black')
plt.setp(bplot['whiskers'], color='black')
plt.setp(bplot['fliers'], color='red', marker='.')
per50s = []
i = 1
for datum in data:
#per50s.append(stats.scoreatpercentile(datum, 50))
t = stats.scoreatpercentile(datum, 50)
per50s.append(t)
#ax1.annotate(str(round(t,3)), xy=(i+0.1, t), xycoords='data', arrowprops=None, fontsize='small', color='black')
i+= 1
#ax1.set_xticks([0.0, 0.5, 1.0, 1.5])
#ax1.set_yscale('log')
ax1.set_ylabel('log10 mutation rate')
ax1.set_ylim(-5, 0)
xtickNames = plt.setp(ax1, xticklabels=labels)
plt.setp(xtickNames, rotation=90, fontsize=6)
plt.savefig(out_prefix+'.pdf', transparent='True', format='pdf')
plt.clf()
def plot_rt_stop_violins(libraries, out_prefix, nucleotides_to_count='ATCG', exclude_constitutive=False):
#Makes violin plots of raw mutation rates
data = []
labels = []
for library in libraries:
labels.append(library.lib_settings.sample_name)
data.append([math.log10(val+1) for val in library.list_rt_stop_rpms(subtract_background=False, subtract_control=False,
nucleotides_to_count=nucleotides_to_count,
exclude_constitutive=exclude_constitutive)])
colormap = uniform_colormaps.viridis
fig = plt.figure(figsize=(5,8))
ax1 = fig.add_subplot(111)
# Hide the grid behind plot objects
ax1.yaxis.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.5)
ax1.set_axisbelow(True)
#ax1.set_xlabel(ylabel)
plt.subplots_adjust(left=0.1, right=0.95, top=0.9, bottom=0.25)
pos = range(1,len(libraries)+1) # starts at 1 to play nice with boxplot
dist = max(pos)-min(pos)
w = min(0.15*max(dist,1.0),0.5)
for library,p in zip(libraries,pos):
d = [math.log10(val+1) for val in library.list_rt_stop_rpms(subtract_background=False, subtract_control=False,
nucleotides_to_count=nucleotides_to_count,
exclude_constitutive=exclude_constitutive)]
k = stats.gaussian_kde(d) #calculates the kernel density
m = k.dataset.min() #lower bound of violin
M = k.dataset.max() #upper bound of violin
x = numpy.arange(m,M,(M-m)/100.) # support for violin
v = k.evaluate(x) #violin profile (density curve)
v = v/v.max()*w #scaling the violin to the available space
plt.fill_betweenx(x,p,v+p,facecolor=colormap((p-1)/float(len(libraries))),alpha=0.3)
plt.fill_betweenx(x,p,-v+p,facecolor=colormap((p-1)/float(len(libraries))),alpha=0.3)
if True:
bplot = plt.boxplot(data,notch=1)
plt.setp(bplot['boxes'], color='black')
plt.setp(bplot['whiskers'], color='black')
plt.setp(bplot['fliers'], color='red', marker='.')
per50s = []
i = 1
for datum in data:
#per50s.append(stats.scoreatpercentile(datum, 50))
t = stats.scoreatpercentile(datum, 50)
per50s.append(t)
#ax1.annotate(str(round(t,3)), xy=(i+0.1, t), xycoords='data', arrowprops=None, fontsize='small', color='black')
i+= 1
#ax1.set_xticks([0.0, 0.5, 1.0, 1.5])
#ax1.set_yscale('log')
ax1.set_ylabel('log10 RT stop RPM +1')
ax1.set_ylim(0, 5)
xtickNames = plt.setp(ax1, xticklabels=labels)
plt.setp(xtickNames, rotation=90, fontsize=6)
plt.savefig(out_prefix+'.pdf', transparent='True', format='pdf')
plt.clf()
def ma_plots_interactive(libraries, out_prefix, nucleotides_to_count='ATCG', exclude_constitutive=False,
max_fold_reduction=0.001, max_fold_increase=100):
"""
:param libraries:
:param out_prefix:
:param nucleotides_to_count:
:param exclude_constitutive:
:return: for each library use bokeh to plot an interactive plot of average magnitude of signal (experimental+control)/2
vs log10 fold change (experimental/control).
Protected and de-protected calls will be colored, based on a fold change cutoff and confidence interval.
All nucleotides will be labelled on mouseover.
"""
from bokeh.plotting import figure, output_file, show, save, ColumnDataSource, gridplot
from bokeh.models import Range1d
from bokeh.models import HoverTool
from collections import OrderedDict
# output to static HTML file
output_file("%s.html" % (out_prefix))
plot_figs=[]
for library in libraries:
mag, fold_change, annotation = [], [], []
prot_mag, prot_fold_change, prot_annotation = [], [], []
deprot_mag, deprot_fold_change, deprot_annotation = [], [], []
for rRNA_name in library.rRNA_mutation_data:
for position in library.rRNA_mutation_data[rRNA_name].nucleotides:
nucleotide = library.rRNA_mutation_data[rRNA_name].nucleotides[position]
if (exclude_constitutive and nucleotide.exclude_constitutive)or nucleotide.identity not in nucleotides_to_count:
continue
else:
protection_call = nucleotide.determine_protection_status(confidence_interval=library.experiment_settings.get_property('confidence_interval_cutoff'),
fold_change_cutoff=library.experiment_settings.get_property('fold_change_cutoff'))
control_fold_change = nucleotide.get_control_fold_change_in_mutation_rate()
avg_mutation_rate = (nucleotide.mutation_rate+nucleotide.get_control_nucleotide().mutation_rate)/2.0
if control_fold_change == 0:
control_fold_change = max_fold_reduction
elif control_fold_change == float('inf'):
control_fold_change = max_fold_increase
if protection_call == 'no_change':
mag.append(avg_mutation_rate)
fold_change.append(control_fold_change)
annotation.append('%s_%s%d' %(rRNA_name,nucleotide.identity,position))
elif protection_call == 'deprotected':
deprot_mag.append(avg_mutation_rate)
deprot_fold_change.append(control_fold_change)
deprot_annotation.append('%s_%s%d' %(rRNA_name,nucleotide.identity,position))
elif protection_call == 'protected':
prot_mag.append(avg_mutation_rate)
prot_fold_change.append(control_fold_change)
prot_annotation.append('%s_%s%d' %(rRNA_name,nucleotide.identity,position))
source = ColumnDataSource(data=dict(x = mag, y = fold_change, label = annotation))
prot_source = ColumnDataSource(data=dict(x = prot_mag, y = prot_fold_change, label = prot_annotation))
deprot_source = ColumnDataSource(data=dict(x = deprot_mag, y = deprot_fold_change,
label = deprot_annotation))
TOOLS = "pan,wheel_zoom,reset,save,hover"
PlotFig = figure(x_axis_label = "avg signal ([%s] + [%s])/2" % (library.lib_settings.sample_name, library.get_normalizing_lib_with_mod().lib_settings.sample_name),
y_axis_label = "fold change [%s]/[%s]" % (library.lib_settings.sample_name, library.get_normalizing_lib_with_mod().lib_settings.sample_name),
y_axis_type="log", x_axis_type="log", tools=TOOLS, toolbar_location="right")
PlotFig.circle("x", "y", size = 5, source=source, color=mod_utils.bokeh_black)
PlotFig.circle("x", "y", size = 5, source=prot_source, color=mod_utils.bokeh_vermillion)
PlotFig.circle("x", "y", size = 5, source=deprot_source, color=mod_utils.bokeh_bluishGreen)
PlotFig.x_range = Range1d(start=0.00001, end=1)
PlotFig.y_range = Range1d(start=.001, end=100)
#adjust what information you get when you hover over it
Hover = PlotFig.select(dict(type=HoverTool))
Hover.tooltips = OrderedDict([("nuc", "@label")])
plot_figs.append([PlotFig])
p = gridplot(plot_figs)
save(p)
def ma_plots_interactive_by_count(libraries, out_prefix, nucleotides_to_count='ATCG', exclude_constitutive=False,
max_fold_reduction=0.001, max_fold_increase=100, lowess_correct=False):
"""
:param libraries:
:param out_prefix:
:param nucleotides_to_count:
:param exclude_constitutive:
:param max_fold_reduction:
:param max_fold_increase:
:param lowess_correct: wether to use lowess regression to correct fold_change data
:return: for each library use bokeh to plot an interactive plot of average magnitude of signal (experimental+control)/2
vs log10 fold change (experimental/control).
Protected and de-protected calls will be colored, based on a fold change cutoff and confidence interval.
All nucleotides will be labelled on mouseover.
"""
from bokeh.plotting import figure, output_file, show, save, ColumnDataSource, gridplot
from bokeh.models import Range1d
from bokeh.models import HoverTool
from collections import OrderedDict
# output to static HTML file
output_file("%s.html" % (out_prefix))
plot_figs=[]
for library in libraries:
mag, fold_change, annotation = [], [], []
prot_mag, prot_fold_change, prot_annotation = [], [], []
deprot_mag, deprot_fold_change, deprot_annotation = [], [], []
if lowess_correct:
library.lowess_correct_mutation_fold_changes(nucleotides_to_count = nucleotides_to_count,
exclude_constitutive=exclude_constitutive,
max_fold_reduction=max_fold_reduction, max_fold_increase=max_fold_increase)
for rRNA_name in library.rRNA_mutation_data:
for position in library.rRNA_mutation_data[rRNA_name].nucleotides:
nucleotide = library.rRNA_mutation_data[rRNA_name].nucleotides[position]
if (exclude_constitutive and nucleotide.exclude_constitutive)or nucleotide.identity not in nucleotides_to_count:
continue
else:
protection_call = nucleotide.determine_protection_status(confidence_interval=library.experiment_settings.get_property('confidence_interval_cutoff'),
fold_change_cutoff=library.experiment_settings.get_property('fold_change_cutoff'), lowess_correct=lowess_correct)
if lowess_correct:
control_fold_change = nucleotide.lowess_fc
else:
control_fold_change = nucleotide.get_control_fold_change_in_mutation_rate()
avg_mutation_rate = (nucleotide.total_mutation_counts+nucleotide.get_control_nucleotide().total_mutation_counts)/2.0
if control_fold_change == 0:
control_fold_change = max_fold_reduction
elif control_fold_change == float('inf'):
control_fold_change = max_fold_increase
if protection_call == 'no_change':
mag.append(avg_mutation_rate)
fold_change.append(control_fold_change)
annotation.append('%s_%s%d' %(rRNA_name,nucleotide.identity,position))
elif protection_call == 'deprotected':
deprot_mag.append(avg_mutation_rate)
deprot_fold_change.append(control_fold_change)
deprot_annotation.append('%s_%s%d' %(rRNA_name,nucleotide.identity,position))
elif protection_call == 'protected':
prot_mag.append(avg_mutation_rate)
prot_fold_change.append(control_fold_change)
prot_annotation.append('%s_%s%d' %(rRNA_name,nucleotide.identity,position))
source = ColumnDataSource(data=dict(x = mag, y = fold_change, label = annotation))
prot_source = ColumnDataSource(data=dict(x = prot_mag, y = prot_fold_change, label = prot_annotation))
deprot_source = ColumnDataSource(data=dict(x = deprot_mag, y = deprot_fold_change, label = deprot_annotation))
fc_log = [math.log(fc, 10) for fc in fold_change]
mag_log = [math.log(m, 10) if m>0 else -1. for m in mag]
lowess_fc_log = lowess(fc_log, mag_log, return_sorted=False)
lowess_fc = 10**lowess_fc_log
lowess_fc_sort_by_mag = [x for (y,x) in sorted(zip(mag,lowess_fc), key=lambda pair: pair[0])]
lowess_line = ColumnDataSource(data=dict(x = sorted(mag), y = lowess_fc_sort_by_mag))
TOOLS = "pan,wheel_zoom,reset,save,hover"
PlotFig = figure(x_axis_label = "average mutation counts",
y_axis_label = "fold change [%s]/[%s]" % (library.lib_settings.sample_name, library.get_normalizing_lib_with_mod().lib_settings.sample_name),
y_axis_type="log", x_axis_type="log", tools=TOOLS, toolbar_location="right")
PlotFig.circle("x", "y", size = 5, source=source, color=mod_utils.bokeh_black)
PlotFig.circle("x", "y", size = 5, source=prot_source, color=mod_utils.bokeh_vermillion)
PlotFig.circle("x", "y", size = 5, source=deprot_source, color=mod_utils.bokeh_bluishGreen)
PlotFig.line("x", "y", source=lowess_line, color='red', line_dash='dashed')
PlotFig.x_range = Range1d(start=.1, end=100000)
PlotFig.y_range = Range1d(start=.001, end=100)
#adjust what information you get when you hover over it
Hover = PlotFig.select(dict(type=HoverTool))
Hover.tooltips = OrderedDict([("nuc", "@label")])
plot_figs.append([PlotFig])
p = gridplot(plot_figs)
save(p)
def ma_plots(libraries, out_prefix, nucleotides_to_count='ATCG', exclude_constitutive=False,
max_fold_reduction=0.001, max_fold_increase=100):
"""
:param libraries:
:param out_prefix:
:param nucleotides_to_count:
:param exclude_constitutive:
:return: for each library use bokeh to plot an interactive plot of magnitude of signal (experimental+control)/2
vs log10 fold change (experimental/control).
Protected and de-protected calls will be colored, based on a fold change cutoff and confidence interval.
All nucleotides will be labelled on mouseover.
"""
output_file = "%s.pdf" % (out_prefix)
plot_figs=[]
num_subplots = len(libraries)
num_plots_wide = math.ceil(math.sqrt(num_subplots))
num_plots_high = num_plots_wide
fig = plt.figure(figsize=(4*num_plots_wide, 4*num_plots_high))
fig.subplots_adjust(wspace=0.4, hspace=0.4)
plot_index =1
for library in libraries:
plot = fig.add_subplot(num_plots_high, num_plots_wide, plot_index)
mag, fold_change, annotation = [], [], []
prot_mag, prot_fold_change, prot_annotation = [], [], []
deprot_mag, deprot_fold_change, deprot_annotation = [], [], []
for rRNA_name in library.rRNA_mutation_data:
for position in library.rRNA_mutation_data[rRNA_name].nucleotides:
nucleotide = library.rRNA_mutation_data[rRNA_name].nucleotides[position]
if (exclude_constitutive and nucleotide.exclude_constitutive)or nucleotide.identity not in nucleotides_to_count:
continue
else:
protection_call = nucleotide.determine_protection_status(confidence_interval=library.experiment_settings.get_property('confidence_interval_cutoff'),
fold_change_cutoff=library.experiment_settings.get_property('fold_change_cutoff'))
control_fold_change = nucleotide.get_control_fold_change_in_mutation_rate()
avg_mutation_rate = (nucleotide.mutation_rate+nucleotide.get_control_nucleotide().mutation_rate)/2.0
if control_fold_change == 0:
control_fold_change = max_fold_reduction
elif control_fold_change == float('inf'):
control_fold_change = max_fold_increase
if protection_call == 'no_change':
mag.append(avg_mutation_rate)
fold_change.append(control_fold_change)
annotation.append('%s_%s%d' %(rRNA_name,nucleotide.identity,position))
elif protection_call == 'deprotected':
deprot_mag.append(avg_mutation_rate)
deprot_fold_change.append(control_fold_change)
deprot_annotation.append('%s_%s%d' %(rRNA_name,nucleotide.identity,position))
elif protection_call == 'protected':
prot_mag.append(avg_mutation_rate)
prot_fold_change.append(control_fold_change)
prot_annotation.append('%s_%s%d' %(rRNA_name,nucleotide.identity,position))
plot.set_xlabel("([%s] + [%s])/2" % (library.lib_settings.sample_name, library.get_normalizing_lib_with_mod().lib_settings.sample_name), fontsize = 8)
plot.set_ylabel("[%s]/[%s]" % (library.lib_settings.sample_name, library.get_normalizing_lib_with_mod().lib_settings.sample_name), fontsize = 8)
plot.set_yscale('log')
plot.set_xscale('log')
plot.scatter(mag, fold_change, color=mod_utils.black, s=3)
plot.scatter(prot_mag, prot_fold_change, color=mod_utils.vermillion, s=5)
plot.scatter(deprot_mag, deprot_fold_change, color=mod_utils.bluishGreen, s=5)
plot.set_xlim(0.00001,1)
plot.set_ylim(1/15.,15)
plot_figs.append(plot)
plot_index+=1
plt.savefig(output_file, transparent='True', format='pdf')
def mutation_rate_scatter(libraries, out_prefix, nucleotides_to_count='ATCG', exclude_constitutive=False):
"""
:param libraries:
:param out_prefix:
:param nucleotides_to_count:
:param exclude_constitutive:
:return: for each library use bokeh to plot an interactive plot of magnitude of signal (experimental+control)/2
vs log10 fold change (experimental/control).
Protected and de-protected calls will be colored, based on a fold change cutoff and confidence interval.
All nucleotides will be labelled on mouseover.
"""
output_file = "%s.pdf" % (out_prefix)
plot_figs=[]
num_subplots = len(libraries)
num_plots_wide = math.ceil(math.sqrt(num_subplots))
num_plots_high = num_plots_wide
fig = plt.figure(figsize=(4*num_plots_wide, 4*num_plots_high))
fig.subplots_adjust(wspace=0.4, hspace=0.4)
plot_index =1
for library in libraries:
plot = fig.add_subplot(num_plots_high, num_plots_wide, plot_index)
x, y, annotation = [], [], []
for rRNA_name in library.rRNA_mutation_data:
for position in library.rRNA_mutation_data[rRNA_name].nucleotides:
nucleotide = library.rRNA_mutation_data[rRNA_name].nucleotides[position]
if (exclude_constitutive and nucleotide.exclude_constitutive)or nucleotide.identity not in nucleotides_to_count:
continue
else:
x.append(nucleotide.mutation_rate)
y.append(nucleotide.get_control_nucleotide().mutation_rate)
plot.set_xlabel("%s misincorporation fraction" % (library.lib_settings.sample_name), fontsize = 8)
plot.set_ylabel("%s misincorporation fraction" % (library.get_normalizing_lib_with_mod().lib_settings.sample_name), fontsize = 8)
plot.set_yscale('log')
plot.set_xscale('log')
x=numpy.array(x)
y=numpy.array(y)
plot.scatter(x, y, color=mod_utils.black, s=3)
logx=numpy.log10(x)
logy=numpy.log10(y)
logx, logy = mod_utils.filter_x_y_pairs(logx, logy)
r, p = stats.pearsonr(logx, logy)
plot.annotate("r^2 = {:.2f}".format(r**2),
xy=(.1, .9), xycoords=plot.transAxes)
plot.set_xlim(0.00001,1)
plot.set_ylim(0.00001,1)
plot_figs.append(plot)
plot_index+=1
plt.savefig(output_file, transparent='True', format='pdf')
def scatter_interactive(libraries, out_prefix, nucleotides_to_count='ATCG', exclude_constitutive=False,
max_fold_reduction=0.001, max_fold_increase=100):
"""
:param libraries:
:param out_prefix:
:param nucleotides_to_count:
:param exclude_constitutive:
:return: for each library use bokeh to plot an interactive plot of average magnitude of signal (experimental+control)/2
vs log10 fold change (experimental/control).
Protected and de-protected calls will be colored, based on a fold change cutoff and confidence interval.
All nucleotides will be labelled on mouseover.
"""
from bokeh.plotting import figure, output_file, show, save, ColumnDataSource, gridplot
from bokeh.models import Range1d
from bokeh.models import HoverTool
from collections import OrderedDict
# output to static HTML file
output_file("%s.html" % (out_prefix))
plot_figs=[]
for library in libraries:
x, y, annotation = [], [], []
prot_x, prot_y, prot_annotation = [], [], []
deprot_x, deprot_y, deprot_annotation = [], [], []
for rRNA_name in library.rRNA_mutation_data:
for position in library.rRNA_mutation_data[rRNA_name].nucleotides:
nucleotide = library.rRNA_mutation_data[rRNA_name].nucleotides[position]
if (exclude_constitutive and nucleotide.exclude_constitutive)or nucleotide.identity not in nucleotides_to_count:
continue
else:
protection_call = nucleotide.determine_protection_status(confidence_interval=library.experiment_settings.get_property('confidence_interval_cutoff'),
fold_change_cutoff=library.experiment_settings.get_property('fold_change_cutoff'))
control_fold_change = nucleotide.get_control_fold_change_in_mutation_rate()
avg_mutation_rate = (nucleotide.mutation_rate+nucleotide.get_control_nucleotide().mutation_rate)/2.0
if control_fold_change == 0:
control_fold_change = max_fold_reduction
elif control_fold_change == float('inf'):
control_fold_change = max_fold_increase
if protection_call == 'no_change':
x.append(nucleotide.get_control_nucleotide().mutation_rate)
y.append(nucleotide.mutation_rate)
annotation.append('%s_%s%d' %(rRNA_name,nucleotide.identity,position))
elif protection_call == 'deprotected':
deprot_x.append(nucleotide.get_control_nucleotide().mutation_rate)
deprot_y.append(nucleotide.mutation_rate)
deprot_annotation.append('%s_%s%d' %(rRNA_name,nucleotide.identity,position))
elif protection_call == 'protected':
prot_x.append(nucleotide.get_control_nucleotide().mutation_rate)
prot_y.append(nucleotide.mutation_rate)
prot_annotation.append('%s_%s%d' %(rRNA_name,nucleotide.identity,position))
source = ColumnDataSource(data=dict(x = x, y = y, label = annotation))
prot_source = ColumnDataSource(data=dict(x = prot_x, y = prot_y, label = prot_annotation))
deprot_source = ColumnDataSource(data=dict(x = deprot_x, y = deprot_y,
label = deprot_annotation))
TOOLS = "pan,wheel_zoom,reset,save,hover"
PlotFig = figure(x_axis_label = "%s misincorporation fraction" % (library.get_normalizing_lib_with_mod().lib_settings.sample_name),
y_axis_label = "%s misincorporation fraction" % (library.lib_settings.sample_name),
y_axis_type="log", x_axis_type="log", tools=TOOLS, toolbar_location="right")
PlotFig.circle("x", "y", size = 5, source=source, color=mod_utils.bokeh_black)
PlotFig.circle("x", "y", size = 5, source=prot_source, color=mod_utils.bokeh_vermillion)
PlotFig.circle("x", "y", size = 5, source=deprot_source, color=mod_utils.bokeh_bluishGreen)
PlotFig.x_range = Range1d(start=0.00001, end=1)
PlotFig.y_range = Range1d(start=0.00001, end=1)
#adjust what information you get when you hover over it
Hover = PlotFig.select(dict(type=HoverTool))
Hover.tooltips = OrderedDict([("nuc", "@label")])
plot_figs.append([PlotFig])
p = gridplot(plot_figs)
save(p)
def ma_plots_by_count(libraries, out_prefix, nucleotides_to_count='ATCG', exclude_constitutive=False,
max_fold_reduction=0.001, max_fold_increase=100, lowess_correct=False):
"""
:param libraries:
:param out_prefix:
:param nucleotides_to_count:
:param exclude_constitutive:
:return: for each library use bokeh to plot an interactive plot of magnitude of signal (experimental+control)/2
vs log10 fold change (experimental/control).
Protected and de-protected calls will be colored, based on a fold change cutoff and confidence interval.
All nucleotides will be labelled on mouseover.
"""
output_file = "%s.pdf" % (out_prefix)
plot_figs=[]
num_subplots = len(libraries)
num_plots_wide = math.ceil(math.sqrt(num_subplots))
num_plots_high = num_plots_wide
fig = plt.figure(figsize=(4*num_plots_wide, 4*num_plots_high))
fig.subplots_adjust(wspace=0.4, hspace=0.4)
plot_index =1
for library in libraries:
if lowess_correct:
library.lowess_correct_mutation_fold_changes(nucleotides_to_count = nucleotides_to_count,
exclude_constitutive=exclude_constitutive,
max_fold_reduction=max_fold_reduction, max_fold_increase=max_fold_increase)
plot = fig.add_subplot(num_plots_high, num_plots_wide, plot_index)
mag, fold_change, annotation = [], [], []
prot_mag, prot_fold_change, prot_annotation = [], [], []
deprot_mag, deprot_fold_change, deprot_annotation = [], [], []
for rRNA_name in library.rRNA_mutation_data:
for position in library.rRNA_mutation_data[rRNA_name].nucleotides:
nucleotide = library.rRNA_mutation_data[rRNA_name].nucleotides[position]
if (exclude_constitutive and nucleotide.exclude_constitutive)or nucleotide.identity not in nucleotides_to_count:
continue
else:
protection_call = nucleotide.determine_protection_status(confidence_interval=library.experiment_settings.get_property('confidence_interval_cutoff'),
fold_change_cutoff=library.experiment_settings.get_property('fold_change_cutoff'),
lowess_correct=lowess_correct)
if lowess_correct:
control_fold_change = nucleotide.lowess_fc
else:
control_fold_change = nucleotide.get_control_fold_change_in_mutation_rate()
avg_mutation_counts = (nucleotide.total_mutation_counts+nucleotide.get_control_nucleotide().total_mutation_counts)/2.0
if control_fold_change == 0:
control_fold_change = max_fold_reduction
elif control_fold_change == float('inf'):
control_fold_change = max_fold_increase
if protection_call == 'no_change':
mag.append(avg_mutation_counts)
fold_change.append(control_fold_change)
annotation.append('%s_%s%d' %(rRNA_name,nucleotide.identity,position))
elif protection_call == 'deprotected':
deprot_mag.append(avg_mutation_counts)
deprot_fold_change.append(control_fold_change)
deprot_annotation.append('%s_%s%d' %(rRNA_name,nucleotide.identity,position))
elif protection_call == 'protected':
prot_mag.append(avg_mutation_counts)
prot_fold_change.append(control_fold_change)
prot_annotation.append('%s_%s%d' %(rRNA_name,nucleotide.identity,position))
fc_log = [math.log(fc, 10) for fc in fold_change]
mag_log = [math.log(m, 10) if m>0 else -1. for m in mag]
lowess_fc_log = lowess(fc_log, mag_log, return_sorted=False)
lowess_fc = 10**lowess_fc_log
lowess_fc_sort_by_mag = [x for (y,x) in sorted(zip(mag,lowess_fc), key=lambda pair: pair[0])]
plot.set_xlabel("average # mutations", fontsize = 8)
plot.set_ylabel("[%s]/[%s]" % (library.lib_settings.sample_name, library.get_normalizing_lib_with_mod().lib_settings.sample_name), fontsize = 8)
plot.set_yscale('log')
plot.set_xscale('log')
plot.scatter(mag, fold_change, color=mod_utils.black, s=3)
plot.scatter(prot_mag, prot_fold_change, color=mod_utils.vermillion, s=5)
plot.scatter(deprot_mag, deprot_fold_change, color=mod_utils.bluishGreen, s=5)
plot.plot(sorted(mag), lowess_fc_sort_by_mag, linestyle='dashed', color='red')
plot.set_xlim(1,1000000)
plot.set_ylim(1/15.,15)
plot_figs.append(plot)
plot_index+=1
plt.savefig(output_file, transparent='True', format='pdf')
def highlight_structure(libraries, out_prefix, nucleotides_to_count='ATCG', exclude_constitutive=False):
"""
:param libraries:
:param out_prefix:
:param nucleotides_to_count:
:param exclude_constitutive:
:return: for each library use bokeh to plot an interactive plot of magnitude of signal (experimental+control)/2
vs log10 fold change (experimental/control).
Protected and de-protected calls will be colored, based on a fold change cutoff and confidence interval.
All nucleotides will be labelled on mouseover.
"""
for library in libraries:
protected_nucleotides = library.get_changed_nucleotides('protected', confidence_interval=library.experiment_settings.get_property('confidence_interval_cutoff'),
fold_change_cutoff=library.experiment_settings.get_property('fold_change_cutoff'))
num_protected = 0
for rRNA in protected_nucleotides:
num_protected += len(protected_nucleotides[rRNA])
deprotected_nucleotides = library.get_changed_nucleotides('deprotected', confidence_interval=library.experiment_settings.get_property('confidence_interval_cutoff'),
fold_change_cutoff=library.experiment_settings.get_property('fold_change_cutoff'))
num_deprotected = 0
for rRNA in deprotected_nucleotides:
num_deprotected += len(deprotected_nucleotides[rRNA])
if num_protected>0 or num_deprotected>0:
output_file = open(os.path.join(out_prefix, "%s.txt" % (library.lib_settings.sample_name)), 'w')
reference_pymol_script_file = open(library.experiment_settings.get_property('pymol_base_script'), 'rU')
for line in reference_pymol_script_file:
if line.startswith('#<insert nucleotide highlighting here>'):
if num_protected>0:
rRNA_selections = []
for rRNA in protected_nucleotides:
if len(protected_nucleotides[rRNA])>0:
rRNA_selections.append('%s and resi %s' % (rRNA, '+'.join([str(nucleotide.position) for
nucleotide in protected_nucleotides[rRNA]])))
outline = 'create protected_nucleotides, %s\n' % (' or '.join(rRNA_selections))
output_file.write(outline)
if num_deprotected>0:
rRNA_selections = []
for rRNA in deprotected_nucleotides:
if len(deprotected_nucleotides[rRNA])>0:
rRNA_selections.append('%s and resi %s' % (rRNA, '+'.join([str(nucleotide.position) for
nucleotide in deprotected_nucleotides[rRNA]])))
outline = 'create deprotected_nucleotides, %s\n' % (' or '.join(rRNA_selections))
output_file.write(outline)
elif line.startswith('#<color groups here>'):
if num_protected>0:
output_file.write('color vermillion, protected_nucleotides\n')
if num_deprotected>0:
output_file.write('color bluish_green, deprotected_nucleotides\n')
elif line.startswith('#<show spheres for changing nucleotides here>'):
if num_protected>0:
output_file.write('show spheres, protected_nucleotides\n')
if num_deprotected>0:
output_file.write('deprotected_nucleotides\n')
else:
output_file.write(line)
reference_pymol_script_file.close()
output_file.close()
def color_by_change(libraries, out_prefix, nucleotides_to_count='ATCG', exclude_constitutive=False, subtract_background=False):
for library in libraries:
log_fold_changes = {}
maxval = 0.0
minval = 0.0
for rRNA_name in library.rRNA_mutation_data:
log_fold_changes[rRNA_name] = {}
for nucleotide in library.rRNA_mutation_data[rRNA_name].nucleotides:
if library.rRNA_mutation_data[rRNA_name].nucleotides[nucleotide].identity in nucleotides_to_count and \
library.rRNA_mutation_data[rRNA_name].nucleotides[nucleotide].\
get_control_fold_change_in_mutation_rate(subtract_background=subtract_background) not in [0.0, float('inf'), float('-inf')]:
if exclude_constitutive and library.rRNA_mutation_data[rRNA_name].nucleotides[nucleotide].exclude_constitutive:
continue
else:
log_fold_changes[rRNA_name][nucleotide] = math.log(library.rRNA_mutation_data[rRNA_name].nucleotides[nucleotide].get_control_fold_change_in_mutation_rate(subtract_background=subtract_background), 10)
maxval = max(maxval, log_fold_changes[rRNA_name][nucleotide])
minval = min(minval, log_fold_changes[rRNA_name][nucleotide])
else:
continue
absmax = max(abs(maxval), abs(minval))
output_file = open(os.path.join(out_prefix, "%s.txt" % (library.lib_settings.sample_name)), 'w')
reference_pymol_script_file = open(library.experiment_settings.get_property('pymol_base_script_colorchange'), 'rU')
for line in reference_pymol_script_file:
if line.startswith('#<insert b-factors>'):
output_file.write('python\n')
output_file.write('cmd.alter(\'all\', \'b=0.0\')\n')
for rRNA_name in log_fold_changes:
for nucleotide in log_fold_changes[rRNA_name]:
output_file.write('cmd.alter(\''+rRNA_name+' and resi '+str(nucleotide)+'\', \'b=float("'+str(log_fold_changes[rRNA_name][nucleotide])+'")\')\n')
output_file.write('python end\n')
elif line.startswith('#<insert spectrum>'):
output_file.write('spectrum b, bluish_green white vermillion, minimum='+str(-absmax)+', maximum='+str(absmax)+'\n')
output_file.write('ramp_new scale, S.c.25S__rRNA, ['+str(-absmax)+',0,'+str(absmax)+'], [bluish_green, white, vermillion]')
else:
output_file.write(line)
reference_pymol_script_file.close()
output_file.close()
def generate_roc_curves(tp_tn_annotations, genome_fasta, outprefix, libraries, rRNA, nucs_to_count):
def winsorize_norm_chromosome_data(mut_density, chromosome, genome_dict, nucs_to_count, to_winsorize = False, low = 0, high = 0.95):
"""
:param read_5p_ends:
:param chromosome:
:param strand:
:param genome_dict:
:param nucs_to_count:
:param low:
:param high:
:return: an array (now zero-indexed from 1-indexed) of densities for the given chromosome on the given strand, winsorized, and only for the given nucleotides
"""
max_position = max(mut_density[chromosome].nucleotides.keys())
density_array =numpy.array([0.0] * max_position)
for position in mut_density[chromosome].nucleotides.keys():
if genome_dict[chromosome][position-1] in nucs_to_count:
density_array[position-1] = mut_density[chromosome].nucleotides[position].mutation_rate
if to_winsorize:
winsorize(density_array, limits = (low, 1-high), inplace = True)
normed_array = density_array/float(max(density_array))
return normed_array
def get_tp_tn(tp_tn_file):
TP = set()
TN = set()
f = open(tp_tn_file)
for line in f:
ll= line.strip('\n').split('\t')
if ll[2] == 'TP':
TP.add(int(ll[0]))
if ll[2] =='TN':
TN.add(int(ll[0]))
f.close()
return TP, TN
def call_positives(density_array, chromosome, genome_dict, nucs_to_count, cutoff):
"""
:param density_array:
:return:a set of called positive positions
I've reverted these to 1-indexed to match the TP and TN calls from the structures
"""
positives = set()
for i in range(len(density_array)):
if genome_dict[chromosome][i] in nucs_to_count:
if density_array[i] >= cutoff:
positives.add(i+1)#adding 1 not necessary for RT stops, since the modified nucleotide is the one 1 upstream of the RT stop!!!
return positives
def plot_ROC_curves(roc_curves, title, out_prefix):
fig = plt.figure(figsize=(8,8))
plot = fig.add_subplot(111)#first a pie chart of mutated nts
colormap = plt.get_cmap('nipy_spectral')
color_index = 0
for name in sorted(roc_curves.keys()):
x, y = roc_curves[name]
area_under_curve = numpy.trapz(numpy.array(y[::-1])/100., x=numpy.array(x[::-1])/100.)
plot.plot(x, y, lw =2, label = '%s %.3f' % (name, area_under_curve), color = colormap(color_index/float(len(roc_curves))))
color_index +=1
plot.plot(numpy.arange(0,100,0.1), numpy.arange(0,100,0.1), lw =1, ls = 'dashed', color = mod_utils.black, label = 'y=x')
plot.set_xlabel('False positive rate (%) (100-specificity)')
plot.set_ylabel('True positive rate (%) (sensitivity)')
plot.set_title(title)
lg=plt.legend(loc=4,prop={'size':10}, labelspacing=0.2)
lg.draw_frame(False)
plt.savefig(out_prefix + '.pdf', transparent='True', format='pdf')
plt.clf()
sample_names = [library.lib_settings.sample_name for library in libraries]
mutation_densities = [library.rRNA_mutation_data for library in libraries]
genome_dict = genome_fasta
normed_density_arrays = [winsorize_norm_chromosome_data(mutation_density, rRNA, genome_dict, nucs_to_count) for mutation_density in mutation_densities]
real_tp, real_tn = get_tp_tn(tp_tn_annotations)
roc_curves = {}
for sample_name in sample_names:
roc_curves[sample_name] = [[],[]]#x and y value arrays for each
stepsize = 0.0001
for cutoff in numpy.arange(0,1.+5*stepsize, stepsize):
for i in range(len(sample_names)):
called_p = call_positives(normed_density_arrays[i], rRNA, genome_dict, nucs_to_count, cutoff)
num_tp_called = len(called_p.intersection(real_tp))#how many true positives called at this cutoff
num_fp_called = len(called_p.intersection(real_tn))#how many fp positives called at this cutoff
roc_curves[sample_names[i]][1].append(100.*num_tp_called/float(len(real_tp)))#TP rate on y axis
roc_curves[sample_names[i]][0].append(100.*num_fp_called/float(len(real_tn)))#FP rate on x axis
plot_ROC_curves(roc_curves, rRNA, outprefix)
def parse_functional_groups(groups_file, delimiter='\t'):
return_dict = defaultdict(list)
f = open(groups_file, 'rU')
lines = f.readlines()
headers = lines[0].strip('\n').split(delimiter)
for line in lines[1:]:
ll= line.strip('\n').split(delimiter)
for i in range(len(ll)):
if not ll[i].strip() =='':
return_dict[headers[i]].append(ll[i])
f.close()
return return_dict
def plot_functional_group_changes(libraries, out_prefix, groups_file, nucleotides_to_count='ATCG', exclude_constitutive=False,
max_fold_reduction=0.001, max_fold_increase=100):
"""
:param libraries:
:param out_prefix:
:param nucleotides_to_count:
:param exclude_constitutive:
:return: for each library make a plot of log10 fold change (experimental/control) between different functional groups.
both as a CDF and as a violin plot
"""
functional_groups = parse_functional_groups(groups_file)
group_names = sorted(functional_groups.keys())
for library in libraries:
cdf_file = "%s_%s_CDF.pdf" % (out_prefix, library.lib_settings.sample_name)
num_plots_wide = 1
num_plots_high = 1
fig = plt.figure(figsize=(4*num_plots_wide, 4*num_plots_high))
plot_index =1
plot = fig.add_subplot(num_plots_high, num_plots_wide, plot_index)
colorindex = 0
all_fold_changes = library.list_mutation_fold_changes(nucleotides_to_count=nucleotides_to_count, exclude_constitutive=exclude_constitutive)
hist, bin_edges = numpy.histogram(all_fold_changes, bins=10000)
cum_hist = numpy.cumsum(hist)
cum_hist = cum_hist/float(max(cum_hist))
plot.plot(bin_edges[:-1], cum_hist, color=mod_utils.colors[0], label='all %d (K-S P)' % (len(all_fold_changes)), lw=2)
for group_name in group_names:
colorindex+=1
group_fold_changes = [nucleotide.get_control_fold_change_in_mutation_rate() for nucleotide in
library.get_nucleotides_from_list(functional_groups[group_name],
nucleotides_to_count=nucleotides_to_count,
exclude_constitutive=exclude_constitutive) if
nucleotide.get_control_fold_change_in_mutation_rate() not in [float('inf'), 0]]
d, p = stats.ks_2samp(all_fold_changes, group_fold_changes)
hist, bin_edges = numpy.histogram(group_fold_changes, bins=10000)
cum_hist = numpy.cumsum(hist)
cum_hist = cum_hist/float(max(cum_hist))
plot.plot(bin_edges[:-1], cum_hist, color=mod_utils.colors[colorindex],label='%s %d (%f)' % (group_name, len(group_fold_changes), p), lw=2)
lg=plt.legend(loc=2,prop={'size':6}, labelspacing=0.2)
lg.draw_frame(False)
plot.set_ylabel("cumulative nucleotide fraction", fontsize = 8)
plot.set_xlabel("[%s]/[%s]" % (library.lib_settings.sample_name, library.get_normalizing_lib_with_mod().lib_settings.sample_name), fontsize = 8)
plot.set_xscale('log')
plot.set_xlim(.1,10)
plot.set_ylim(0, 1)
plt.savefig(cdf_file, transparent='True', format='pdf') | {
"repo_name": "borisz264/mod_seq",
"path": "mod_plotting.py",
"copies": "1",
"size": "62033",
"license": "mit",
"hash": 5215933679536626000,
"line_mean": 55.3945454545,
"line_max": 223,
"alpha_frac": 0.6142698241,
"autogenerated": false,
"ratio": 3.548595618099651,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9618462924261684,
"avg_score": 0.008880503587593352,
"num_lines": 1100
} |
__author__ = 'boris'
"""
Based on the Rouskin DMS-seq paper:
True Positives: Bases that are unpaired in the secondary structure, and the reactive atom has a solvent accessible
surface area (to a 3A radius sphere) of greater than 2A squared.
True Negatives: are Watson-crick paired (A-U or C-G) in the secondary structure model
"""
import mod_utils
import sys
from unused_scripts.rna import rna
class rRNA:
def __init__(self, bpseq_filename):
self.nucleotides = {}
self.parse_bpseq(bpseq_filename)
def parse_bpseq(self, bpseq_filename):
"""
:param bpseq_filename:
:return: a dictionary mapping position
"""
f = open(bpseq_filename, 'rU')
lines = f.readlines()
for line in lines[4:]:
nt_num, nt_ident, paired_to = line.rstrip().split(' ')
self.nucleotides[int(nt_num)] = nucleotide(self, nt_num, nt_ident, paired_to)
f.close()
def parse_rouskin_accessibility(self, filenames):
for filename in filenames:
f = open(filename, 'rU')
for line in f:
ll = line.rstrip().split('\t')
self.nucleotides[int(ll[0])].sasa = float(ll[1])
f.close()
def parse_zinshteyn_accessibility(self, filename):
f = open(filename)
for line in f:
ll = line.rstrip().split('\t')
assert rna(ll[1]) == self.nucleotides[int(ll[0])].identity
self.nucleotides[int(ll[0])].sasa = float(ll[2])
f.close()
def write_to_file(self, sasa_cutoff, nucs_to_test, output_prefix):
f = open('%s_%.1f_%s.txt' % (output_prefix, sasa_cutoff, nucs_to_test), 'w')
for nt_pos in self.nucleotides:
nuc = self.nucleotides[nt_pos]
assert nt_pos == nuc.position
assert not (nuc.is_true_positive(sasa_cutoff) and nuc.is_true_negative())
if nuc.identity in nucs_to_test:
if nuc.is_true_positive(sasa_cutoff):
result_string = 'TP'
elif nuc.is_true_negative():
result_string = 'TN'
else:
result_string = 'X'
else:
result_string = 'X'
f.write('%d\t%s\t%s\n' % (nuc.position, nuc.identity, result_string))
class nucleotide:
def __init__(self, rRNA, position, identity, paired_to):
self.rRNA = rRNA
self.identity = identity
self.position = int(position)
self.paired_to = int(paired_to)
self.sasa = None #solvent accessible surface ares
def is_WC_paired(self):
if not self.paired_to == 0:
if mod_utils.revComp(self.identity, isRNA = True) == self.rRNA.nucleotides[self.paired_to].identity:
#if this nucleotide is the WC complement of the one it's paired to, return True
return True
return False
def is_true_positive(self, sasa_cutoff):
if (not self.is_WC_paired()) and (not self.sasa == None) and self.sasa > sasa_cutoff:
return True
else:
return False
def is_true_negative(self):
if self.is_WC_paired():
return True
else:
return False
def main():
bpseq_filename, outprefix = sys.argv[1:3]
#rouskin_sasa_files = sys.argv[3:]
zin_sasa_file = sys.argv[3]
rRNA_data = rRNA(bpseq_filename)
#rRNA_data.parse_rouskin_accessibility(rouskin_sasa_files)
rRNA_data.parse_zinshteyn_accessibility(zin_sasa_file)
rRNA_data.write_to_file(2.0, 'AC', outprefix)
if __name__ == '__main__':
main() | {
"repo_name": "borisz264/mod_seq",
"path": "structure_ROC_curves/compute_true_positives_negative.py",
"copies": "1",
"size": "3646",
"license": "mit",
"hash": -5654917576875624000,
"line_mean": 33.4056603774,
"line_max": 118,
"alpha_frac": 0.5781678552,
"autogenerated": false,
"ratio": 3.269955156950673,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4348123012150673,
"avg_score": null,
"num_lines": null
} |
__author__ = 'boris'
"""
inputs:
outfolder - where to put all the results
control_file_name - a pickled dict of [strand][chromosome][position] = background-subtracted mutations/coverage
output from normalize_to_control_make_wig.py - this is already a comparison of modifier to no modifier.
experimental_file_names - any number of files, of same format as control file, to be compared to the control.
outputs:
for each file, a WIG file with the max rescaled to 1
?add pseudocounts?
for each experimental file, a WIG of the log2 ratio of experimental/control
for each experimental file, a WIG of the log2 ratio of experimental/control, which were rescaled before comparison.
for each experimental file, a pickled dictionary of the log2 ratio, in the same format as above
for each experimental file, a pickled dictionary of the log2 ratio, previously rescaled as above
"""
import sys
import mod_utils
import os
import gzip
from scipy.stats.mstats import winsorize
import matplotlib.pyplot as plt
from collections import defaultdict
import numpy
import math
plt.rcParams['pdf.fonttype'] = 42 #leaves most text as actual text in PDFs, not outlines
def write_wig(mutation_dict, sample_name, output_prefix):
"""
:param mutation_dict: a pickled dict of [strand][chromosome][position] = mutations/coverage
:param output_prefix:
:return:
"""
score_table = open(output_prefix+'_scores.txt', 'w')
plusWig = gzip.open(output_prefix+'_plus.wig.gz', 'w')
#minusWig = gzip.open(output_prefix+'_minus.wig.gz', 'w')
plusWig.write('track type=wiggle_0 name=%s\n' % (sample_name+'_plus'))
#minusWig.write('track type=wiggle_0 name=%s\n' % (sample_name+'_minus'))
allChrs=set(mutation_dict['+'].keys()).union(set(mutation_dict['-'].keys()))
for chr in allChrs:
#minPos = min([min(weightedReads['+'][chr].keys()), min(weightedReads['-'][chr].keys())])
#maxPos = max([max(weightedReads['+'][chr].keys()), max(weightedReads['-'][chr].keys())])
plusWig.write('variableStep chrom=%s\n' % (chr))
#minusWig.write('variableStep chrom=%s\n' % (chr))
if chr in mutation_dict['+']:
for i in sorted(mutation_dict['+'][chr].keys()):
plusWig.write('%d\t%f\n' % (i, mutation_dict['+'][chr][i]))
score_table.write('%s_%d\t%f\n' % (chr, i, mutation_dict['+'][chr][i]))
#if chr in mutation_dict['-']:
#for i in sorted(mutation_dict['-'][chr].keys()):
#minusWig.write('%d\t%f\n' % (i, mutation_dict['-'][chr][i]/mutation_dict))
plusWig.close()
score_table.close()
#minusWig.close()
def normalize_dict_to_max(mutation_dict, winsorize_data = False, winsorization_limits = (0, 0.95)):
all_values = []
normed_dict = {}
for strand in mutation_dict:
normed_dict[strand] = {}
for chromosome in mutation_dict[strand]:
normed_dict[strand][chromosome] = {}
#print mutation_dict[strand][chromosome].values()
all_values += mutation_dict[strand][chromosome].values()
#print all_values
if winsorize_data:
winsorize(all_values, limits = (winsorization_limits[0], 1-winsorization_limits[1]), inplace = True)
max_value = float(max(all_values))
for strand in mutation_dict:
for chromosome in mutation_dict[strand]:
for position in mutation_dict[strand][chromosome]:
val = mutation_dict[strand][chromosome][position]
if val < min(all_values):
val = min(all_values)
if val > max(all_values):
val = max(all_values)
normed_dict[strand][chromosome][position] = val/max_value
return normed_dict
def plot_weighted_nts_pie(background_subtracted, fasta_genome, title, out_prefix):
genome = mod_utils.convertFastaToDict(fasta_genome)
fig = plt.figure(figsize=(8,8))
plot = fig.add_subplot(111)#a pie chart of mutated nts weighted by background-subtracted counts
labels = "ATCG"
nt_counts = defaultdict(float)
for strand in background_subtracted:
for chromosome in background_subtracted[strand]:
for position in background_subtracted[strand][chromosome]:
nt = genome[chromosome][position-1]
nt_counts[nt] += background_subtracted[strand][chromosome][position]
sizes = numpy.array([nt_counts[nt] for nt in labels])
total = float(sum(sizes))
sizes = sizes/total
merged_labels = ['%s %.3f' % (labels[i], sizes[i]) for i in range(len(sizes))]
plot.pie(sizes, labels = merged_labels, colors = mod_utils.rainbow)
plot.set_title(title)
plt.savefig(out_prefix + '.pdf', transparent='True', format='pdf')
plt.clf()
def compare_to_control(experiment_dict, control_dict):
"""
:param experiment_dict:
:param normalization_dict:
:return: subtracted_dict - normalization value subtracted from experimental at every position
"""
ratio_dict = {}
for strand in experiment_dict:
ratio_dict[strand] = {}
for chromosome in experiment_dict[strand]:
ratio_dict[strand][chromosome] = {}
for position in experiment_dict[strand][chromosome]:
try:
#dividing by zero will cause issues here
ratio_dict[strand][chromosome][position] = math.log(float(experiment_dict[strand][chromosome][position])/float(control_dict[strand][chromosome][position]), 2)
except:
pass
return ratio_dict
def normed_mutation_rate_histogram(normalized_mutations, dataset_names, output_prefix, title = '', xlim= (0,1), min = 0, max = 1, step = 0.01):
fig = plt.figure(figsize=(16,16))
plot = fig.add_subplot(111)
bins = numpy.arange(xlim[0],xlim[1],step)
bins = numpy.append(bins, max+step)
bins = numpy.append([min-step], bins)
for i in range(len(dataset_names)):
mutation_densities = []
for strand in normalized_mutations[i]:
for chromosome in normalized_mutations[i][strand]:
mutation_densities = mutation_densities + [val for val in normalized_mutations[i][strand][chromosome].values()]
counts, edges = numpy.histogram(mutation_densities, bins = bins)
#plot.hist(mutation_densities, color = mod_utils.colors [i], bins = bins, label=dataset_names[i])
counts = [0]+list(counts)+[0]
edges = [0]+list(edges)+[edges[-1]]
plot.fill(edges[:-1], numpy.array(counts), alpha = 0.3, color = mod_utils.colors[i], lw=0)
plot.plot(edges[:-1], numpy.array(counts), color = mod_utils.colors[i], label=dataset_names[i], lw=2)
plot.set_xlim(xlim[0]-step,xlim[1]+step)
#plot.set_xticks(numpy.arange(0,10)+0.5)
#plot.set_xticklabels(numpy.arange(0,10))
plot.set_xlabel('mutations/coverage')
plot.set_ylabel("# positions")
plot.set_title(title)
lg=plt.legend(loc=2,prop={'size':10}, labelspacing=0.2)
lg.draw_frame(False)
#plot.set_yscale('log')
#plot.set_title(title)
plt.savefig(output_prefix + '_mut_density.pdf', transparent='True', format='pdf')
plt.clf()
def main():
outfolder, genome_fasta, normalization_file_name = sys.argv[1:4]
experimental_file_names = sys.argv[4:]
control_dict = mod_utils.unPickle(normalization_file_name)
rescaled_control_dict = normalize_dict_to_max(control_dict)
norm_name = '.'.join(os.path.basename(normalization_file_name).split('.')[:-1])
experimental_dict_names = ['.'.join(os.path.basename(file_name).split('.')[:-1]) for file_name in experimental_file_names]
experimental_dicts = [mod_utils.unPickle(file_name) for file_name in experimental_file_names]
rescaled_experimental_dicts = [normalize_dict_to_max(exp_dict) for exp_dict in experimental_dicts]
print experimental_dict_names, norm_name
normed_mutation_rate_histogram(rescaled_experimental_dicts, experimental_dict_names, os.path.join(outfolder, '%s_rescaled_mutation_rate_histogram' % norm_name), title='mutation rate, rescaled to max', xlim = (0, 0.1), min = 0, max =1, step = 0.001)
comparisons = []
rescaled_comparisons = []
write_wig(control_dict, norm_name, os.path.join(outfolder, norm_name))
for i in range(len(experimental_dict_names)):
write_wig(rescaled_experimental_dicts[i], experimental_dict_names[i], os.path.join(outfolder, experimental_dict_names[i]))
comparison_log2_ratios = compare_to_control(experimental_dicts[i], control_dict)
rescaled_comparison_log2_ratios = compare_to_control(rescaled_experimental_dicts[i], rescaled_control_dict)
comparisons.append(comparison_log2_ratios)
rescaled_comparisons.append(rescaled_comparison_log2_ratios)
mod_utils.makePickle(comparison_log2_ratios, os.path.join(outfolder, experimental_dict_names[i]+'_comparison_log2.pkl'))
#mod_utils.makePickle(rescaled_comparison_log2_ratios, os.path.join(outfolder, experimental_dict_names[i]+'_rescaled_comparison_log2.pkl'))
write_wig(comparison_log2_ratios, experimental_dict_names[i]+'_comparison_log2', os.path.join(outfolder, experimental_dict_names[i]+'_comparison_log2'))
#write_wig(rescaled_comparison_log2_ratios, experimental_dict_names[i]+'_rescaled)comparison_log2', os.path.join(outfolder, experimental_dict_names[i]+'_rescaled_comparison_log2'))
#try:
# plot_weighted_nts_pie(background_subtracted, genome_fasta, '%s backround-subtracted fractions' % experimental_dict_names[i], os.path.join(outfolder, experimental_dict_names[i]+'_sub_pie'))
#except:
# pass
#print comparisons
#print rescaled_comparisons
normed_mutation_rate_histogram(comparisons, experimental_dict_names, os.path.join(outfolder, '%s_comparison_histogram' % norm_name), title='log2 experiment/control', xlim = (-10, 10), min = -100, max =100, step = 0.1)
#normed_mutation_rate_histogram(rescaled_comparisons, experimental_dict_names, os.path.join(outfolder, '%s_rescaled_comparison_histogram' % norm_name), title='log2 rescaled experiment/control', xlim = (-10, 10), min = -100, max =100, step = 0.1)
main() | {
"repo_name": "borisz264/mod_seq",
"path": "unused_scripts/compare_samples.py",
"copies": "1",
"size": "10227",
"license": "mit",
"hash": 992569476420671600,
"line_mean": 52.5497382199,
"line_max": 252,
"alpha_frac": 0.6650044001,
"autogenerated": false,
"ratio": 3.4055944055944054,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9516956705651354,
"avg_score": 0.01072842000861036,
"num_lines": 191
} |
__author__ = 'boris'
"""
inputs:
outfolder - where to put all the results
normalization_file_name - a pickled dict of [strand][chromosome][position] = mutations/coverage
output from count_reads_and_mismatches.py - this is from a sample where no modifying reagent was added.
experimental_file_names - any number of files, of same format as normalization file, to be normalized by the normalization file
outputs:
for each file, a WIG file of the mutation rate, normalized by the coverage within the same sample
for each experimental file, a WIG of the coverage-normalized mutation rate, normalized again by the control (by simple subtraction). Minimum is set to zero.
for each experimental file, a pickled dictionary of the coverage-normalized mutation rate, normalized again by the control, in the same format as above
"""
import sys
import mod_utils
import os
import gzip
from scipy.stats.mstats import winsorize
import matplotlib.pyplot as plt
from collections import defaultdict
import numpy
plt.rcParams['pdf.fonttype'] = 42 #leaves most text as actual text in PDFs, not outlines
def write_wig(mutation_dict, sample_name, output_prefix):
"""
:param mutation_dict: a pickled dict of [strand][chromosome][position] = mutations/coverage
:param output_prefix:
:return:
"""
plusWig = gzip.open(output_prefix+'_plus.wig.gz', 'w')
#minusWig = gzip.open(output_prefix+'_minus.wig.gz', 'w')
plusWig.write('track type=wiggle_0 name=%s\n' % (sample_name+'_plus'))
#minusWig.write('track type=wiggle_0 name=%s\n' % (sample_name+'_minus'))
allChrs=set(mutation_dict['+'].keys()).union(set(mutation_dict['-'].keys()))
for chr in allChrs:
#minPos = min([min(weightedReads['+'][chr].keys()), min(weightedReads['-'][chr].keys())])
#maxPos = max([max(weightedReads['+'][chr].keys()), max(weightedReads['-'][chr].keys())])
plusWig.write('variableStep chrom=%s\n' % (chr))
#minusWig.write('variableStep chrom=%s\n' % (chr))
if chr in mutation_dict['+']:
for i in sorted(mutation_dict['+'][chr].keys()):
plusWig.write('%d\t%f\n' % (i, mutation_dict['+'][chr][i]))
#if chr in mutation_dict['-']:
#for i in sorted(mutation_dict['-'][chr].keys()):
#minusWig.write('%d\t%f\n' % (i, mutation_dict['-'][chr][i]/mutation_dict))
plusWig.close()
#minusWig.close()
def normalize_dict_to_max(mutation_dict, winsorize_data = False, winsorization_limits = (0, 0.95)):
all_values = []
normed_dict = {}
for strand in mutation_dict:
normed_dict[strand] = {}
for chromosome in mutation_dict[strand]:
normed_dict[strand][chromosome] = {}
#print mutation_dict[strand][chromosome].values()
all_values += mutation_dict[strand][chromosome].values()
#print all_values
if winsorize_data:
winsorize(all_values, limits = (winsorization_limits[0], 1-winsorization_limits[1]), inplace = True)
max_value = float(max(all_values))
for strand in mutation_dict:
for chromosome in mutation_dict[strand]:
for position in mutation_dict[strand][chromosome]:
val = mutation_dict[strand][chromosome][position]
if val < min(all_values):
val = min(all_values)
if val > max(all_values):
val = max(all_values)
normed_dict[strand][chromosome][position] = val/max_value
return normed_dict
def plot_weighted_nts_pie(background_subtracted, fasta_genome, title, out_prefix):
genome = mod_utils.convertFastaToDict(fasta_genome)
fig = plt.figure(figsize=(8,8))
plot = fig.add_subplot(111)#a pie chart of mutated nts weighted by background-subtracted counts
labels = "ATCG"
nt_counts = defaultdict(float)
for strand in background_subtracted:
for chromosome in background_subtracted[strand]:
for position in background_subtracted[strand][chromosome]:
nt = genome[chromosome][position-1]
nt_counts[nt] += background_subtracted[strand][chromosome][position]
sizes = numpy.array([nt_counts[nt] for nt in labels])
total = float(sum(sizes))
sizes = sizes/total
merged_labels = ['%s %.3f' % (labels[i], sizes[i]) for i in range(len(sizes))]
plot.pie(sizes, labels = merged_labels, colors = mod_utils.rainbow)
plot.set_title(title)
plt.savefig(out_prefix + '.pdf', transparent='True', format='pdf')
plt.clf()
def subtract_background(experiment_dict, normalization_dict):
"""
:param experiment_dict:
:param normalization_dict:
:return: subtracted_dict - normalization value subtracted from experimental at every position
"""
subtracted_dict = {}
for strand in experiment_dict:
subtracted_dict[strand] = {}
for chromosome in experiment_dict[strand]:
subtracted_dict[strand][chromosome] = {}
for position in experiment_dict[strand][chromosome]:
if position in experiment_dict[strand][chromosome] and position in normalization_dict[strand][chromosome]:
subtracted_dict[strand][chromosome][position] = max(experiment_dict[strand][chromosome][position]-normalization_dict[strand][chromosome][position], 0)
return subtracted_dict
def normed_mutation_rate_histogram(normalized_mutations, dataset_names, output_prefix, title = ''):
fig = plt.figure(figsize=(16,16))
plot = fig.add_subplot(111)
step = 0.0001
max = 0.01
bins = numpy.arange(0,max,step)
bins = numpy.append(bins, 1+step)
for i in range(len(dataset_names)):
mutation_densities = []
for strand in normalized_mutations[i]:
for chromosome in normalized_mutations[i][strand]:
mutation_densities = mutation_densities + [val for val in normalized_mutations[i][strand][chromosome].values() if val > 0]
counts, edges = numpy.histogram(mutation_densities, bins = bins)
#plot.hist(mutation_densities, color = mod_utils.colors [i], bins = bins, label=dataset_names[i])
counts = [0]+list(counts)+[0]
edges = [0]+list(edges)+[edges[-1]]
plot.fill(edges[:-1], numpy.array(counts), alpha = 0.3, color = mod_utils.colors[i], lw=0)
plot.plot(edges[:-1], numpy.array(counts), color = mod_utils.colors[i], label=dataset_names[i], lw=2)
plot.set_xlim(0,max+step)
#plot.set_xticks(numpy.arange(0,10)+0.5)
#plot.set_xticklabels(numpy.arange(0,10))
plot.set_xlabel('mutations/coverage')
plot.set_ylabel("# positions")
plot.set_title(title)
lg=plt.legend(loc=2,prop={'size':10}, labelspacing=0.2)
lg.draw_frame(False)
#plot.set_yscale('log')
#plot.set_title(title)
plt.savefig(output_prefix + '_mut_density.pdf', transparent='True', format='pdf')
plt.clf()
def main():
outfolder, genome_fasta, normalization_file_name = sys.argv[1:4]
experimental_file_names = sys.argv[4:]
mod_utils.make_dir(outfolder)
normalization_dict = mod_utils.unPickle(normalization_file_name)
norm_name = '.'.join(os.path.basename(normalization_file_name).split('.')[:-2])
experimental_dict_names = ['.'.join(os.path.basename(file_name).split('.')[:-2]) for file_name in experimental_file_names]
experimental_dicts = [mod_utils.unPickle(file_name) for file_name in experimental_file_names]
normed_mutation_rate_histogram(experimental_dicts, experimental_dict_names, os.path.join(outfolder, 'mutation_rate_histogram'), title='nonzero positions')
background_subtracted_sets = []
write_wig(normalization_dict, norm_name, os.path.join(outfolder, norm_name))
for i in range(len(experimental_dict_names)):
write_wig(experimental_dicts[i], experimental_dict_names[i], os.path.join(outfolder, experimental_dict_names[i]))
background_subtracted = subtract_background(experimental_dicts[i], normalization_dict)
background_subtracted_sets.append(background_subtracted)
mod_utils.makePickle(background_subtracted, os.path.join(outfolder, experimental_dict_names[i]+'_subtracted.pkl'))
write_wig(background_subtracted, experimental_dict_names[i]+'_subtracted', os.path.join(outfolder, experimental_dict_names[i]+'_subtracted'))
try:
plot_weighted_nts_pie(background_subtracted, genome_fasta, '%s backround-subtracted fractions' % experimental_dict_names[i], os.path.join(outfolder, experimental_dict_names[i]+'_sub_pie'))
except:
pass
normed_mutation_rate_histogram(background_subtracted_sets, experimental_dict_names, os.path.join(outfolder, 'back_subtracted_mutation_rate_histogram'), title = 'nonzero positions, background subtracted')
main() | {
"repo_name": "borisz264/mod_seq",
"path": "unused_scripts/normalize_to_control_make_wig.py",
"copies": "1",
"size": "8799",
"license": "mit",
"hash": 2589449244232951000,
"line_mean": 51.0710059172,
"line_max": 207,
"alpha_frac": 0.6693942493,
"autogenerated": false,
"ratio": 3.528067361668003,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9646193503362148,
"avg_score": 0.01025362152117078,
"num_lines": 169
} |
__author__ = 'boris'
"""
inputs:
outprefix
bundle 1
bundle 2
bundle 3
bundle 4
bundle 5 - the 5 pdb files from the 4v88 bundle
reactivity_values - a pickled dict of [chromosome][position] = reactivity_value or change, such as from compare_samples.py
outputs:
the 5 PDB files in the bundle, with b factors replaced with reactivity scores for the corresponding rRNA residues.
"""
import sys
import mod_utils
import os
import gzip
from scipy.stats.mstats import winsorize
import matplotlib.pyplot as plt
from collections import defaultdict
import numpy
import math
plt.rcParams['pdf.fonttype'] = 42 #leaves most text as actual text in PDFs, not outlines
def write_wig(mutation_dict, sample_name, output_prefix):
"""
:param mutation_dict: a pickled dict of [strand][chromosome][position] = mutations/coverage
:param output_prefix:
:return:
"""
score_table = open(output_prefix+'_scores.txt', 'w')
plusWig = gzip.open(output_prefix+'_plus.wig.gz', 'w')
#minusWig = gzip.open(output_prefix+'_minus.wig.gz', 'w')
plusWig.write('track type=wiggle_0 name=%s\n' % (sample_name+'_plus'))
#minusWig.write('track type=wiggle_0 name=%s\n' % (sample_name+'_minus'))
allChrs=set(mutation_dict.keys()).union(set(mutation_dict['-'].keys()))
for chr in allChrs:
#minPos = min([min(weightedReads['+'][chr].keys()), min(weightedReads['-'][chr].keys())])
#maxPos = max([max(weightedReads['+'][chr].keys()), max(weightedReads['-'][chr].keys())])
plusWig.write('variableStep chrom=%s\n' % (chr))
#minusWig.write('variableStep chrom=%s\n' % (chr))
if chr in mutation_dict:
for i in sorted(mutation_dict[chr].keys()):
plusWig.write('%d\t%f\n' % (i, mutation_dict[chr][i]))
score_table.write('%s_%d\t%f\n' % (chr, i, mutation_dict['+'][chr][i]))
#if chr in mutation_dict['-']:
#for i in sorted(mutation_dict['-'][chr].keys()):
#minusWig.write('%d\t%f\n' % (i, mutation_dict['-'][chr][i]/mutation_dict))
plusWig.close()
score_table.close()
#minusWig.close()
def normalize_dict_to_max(mutation_dict, winsorize_data = False, winsorization_limits = (0, 0.95)):
all_values = []
normed_dict = {}
for chromosome in mutation_dict:
normed_dict[chromosome] = {}
#print mutation_dict[strand][chromosome].values()
all_values += mutation_dict[chromosome].values()
if winsorize_data:
winsorize(all_values, limits = (winsorization_limits[0], 1-winsorization_limits[1]), inplace = True)
max_value = float(max(all_values))
min_value = float(min(all_values))
norm_value = max(max_value, -1*min_value)
print max_value
for chromosome in mutation_dict:
for position in mutation_dict[chromosome]:
val = mutation_dict[chromosome][position]
if val < min(all_values):
val = min(all_values)
if val > max(all_values):
val = max(all_values)
normed_dict[chromosome][position] = val/norm_value
return normed_dict
def split_by_n(line, n=6):
"""
trims endline, and returns set of chunks of length 6, each of which has whitespace stripped
:param line:
:param n:
:return:
"""
return [line[i:i+n].strip() for i in range(0, len(line), 6)]
#rRNA_assignments = {3:{'d':"S.c.18S_rRNA"}, 1:{'A':"S.c.18S_rRNA"}, 2:{'A':"S.c.25S__rRNA", 'B':"S.c.5S___rRNA", 'C':"S.c.5.8S_rRNA"} , 4:{'K':"S.c.25S__rRNA", 'L':"S.c.5S___rRNA", 'M':"S.c.5.8S_rRNA"}}
#for 4V88:
rRNA_assignments = {3:{'d':"S.c.18S_rRNA"}, 1:{'A':"S.c.18S_rRNA"}, 2:{'A':"S.c.25S__rRNA", 'B':"S.c.5S___rRNA", 'C':"S.c.5.8S_rRNA"} , 4:{'I':"S.c.25S__rRNA", 'L':"S.c.5S___rRNA", 'M':"S.c.5.8S_rRNA"}}
#for 4V6I:
#rRNA_assignments = {2:{'S':"S.c.18S_rRNA"}, 3:{'A':"S.c.25S__rRNA", 'C':"S.c.5S___rRNA", 'B':"S.c.5.8S_rRNA"}}
#for 4U3U:
#rRNA_assignments = {1:{'A':"S.c.18S_rRNA"}, 2:{'A':"S.c.25S__rRNA", 'C':"S.c.5S___rRNA", 'B':"S.c.5.8S_rRNA"}}
def main():
outprefix, bundle1, bundle2, bundle3, bundle4, bundle5, datafile_name = sys.argv[1:8]
bundles = [bundle1, bundle2, bundle3, bundle4, bundle5]
reactivities = mod_utils.unPickle(datafile_name)
scaling_factor = 1000. #all values will be multiplied byt his factor. This is necessary because the values produced are often very small, and the B factors in the PDB file are limited to 6 characters
for i in range(1,6):
infile = open(bundles[i-1])
outfile = open(outprefix+'_bundle'+str(i)+'.pdb' ,'w')
for line in infile:
if line.startswith('ATOM'):
chain = line[21]
resi = int(line[22:28].strip())
#print i, chain, resi
#print rRNA_assignments[i][chain]
#print reactivities[rRNA_assignments[i][chain]]
if i in rRNA_assignments and chain in rRNA_assignments[i] and resi in reactivities[rRNA_assignments[i][chain]]:
insert = '%6.3f' % (scaling_factor*reactivities[rRNA_assignments[i][chain]][resi])
new_line = '%s%s%s' % (line[:60], insert[:6], line[66:])
assert len(line) == len(new_line)
else:
new_line = '%s%6.4f%s' % (line[:60], 0.0, line[66:])
assert len(line) == len(new_line)
elif line.startswith("ANISOU") or line.startswith("HETATM"):
new_line = '' #remove the anisotropic b factors, I don't need them
else:
new_line = line
outfile.write(new_line)
infile.close()
outfile.close()
main() | {
"repo_name": "borisz264/mod_seq",
"path": "unused_scripts/map_onto_rRNA_structure_shapemapper.py",
"copies": "1",
"size": "5711",
"license": "mit",
"hash": -3853618376834659300,
"line_mean": 40.6934306569,
"line_max": 203,
"alpha_frac": 0.5928909123,
"autogenerated": false,
"ratio": 3.0572805139186294,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.41501714262186296,
"avg_score": null,
"num_lines": null
} |
__author__ = 'boris'
"""
inputs:
outprefix
bundle 1
bundle 2
bundle 3
bundle 4
bundle 5 - the 5 pdb files from the 4v88 bundle
reactivity_values - a pickled dict of [strand][chromosome][position] = reactivity_value or change, such as from compare_samples.py
outputs:
the 5 PDB files in the bundle, with b factors replaced with reactivity scores for the corresponding rRNA residues.
"""
import sys
import mod_utils
import os
import gzip
from scipy.stats.mstats import winsorize
import matplotlib.pyplot as plt
from collections import defaultdict
import numpy
import math
plt.rcParams['pdf.fonttype'] = 42 #leaves most text as actual text in PDFs, not outlines
def write_wig(mutation_dict, sample_name, output_prefix):
"""
:param mutation_dict: a pickled dict of [strand][chromosome][position] = mutations/coverage
:param output_prefix:
:return:
"""
score_table = open(output_prefix+'_scores.txt', 'w')
plusWig = gzip.open(output_prefix+'_plus.wig.gz', 'w')
#minusWig = gzip.open(output_prefix+'_minus.wig.gz', 'w')
plusWig.write('track type=wiggle_0 name=%s\n' % (sample_name+'_plus'))
#minusWig.write('track type=wiggle_0 name=%s\n' % (sample_name+'_minus'))
allChrs=set(mutation_dict['+'].keys()).union(set(mutation_dict['-'].keys()))
for chr in allChrs:
#minPos = min([min(weightedReads['+'][chr].keys()), min(weightedReads['-'][chr].keys())])
#maxPos = max([max(weightedReads['+'][chr].keys()), max(weightedReads['-'][chr].keys())])
plusWig.write('variableStep chrom=%s\n' % (chr))
#minusWig.write('variableStep chrom=%s\n' % (chr))
if chr in mutation_dict['+']:
for i in sorted(mutation_dict['+'][chr].keys()):
plusWig.write('%d\t%f\n' % (i, mutation_dict['+'][chr][i]))
score_table.write('%s_%d\t%f\n' % (chr, i, mutation_dict['+'][chr][i]))
#if chr in mutation_dict['-']:
#for i in sorted(mutation_dict['-'][chr].keys()):
#minusWig.write('%d\t%f\n' % (i, mutation_dict['-'][chr][i]/mutation_dict))
plusWig.close()
score_table.close()
#minusWig.close()
def normalize_dict_to_max(mutation_dict, winsorize_data = False, winsorization_limits = (0, 0.95)):
all_values = []
normed_dict = {}
for strand in mutation_dict:
normed_dict[strand] = {}
for chromosome in mutation_dict[strand]:
normed_dict[strand][chromosome] = {}
#print mutation_dict[strand][chromosome].values()
all_values += mutation_dict[strand][chromosome].values()
#print all_values
if winsorize_data:
winsorize(all_values, limits = (winsorization_limits[0], 1-winsorization_limits[1]), inplace = True)
max_value = float(max(all_values))
for strand in mutation_dict:
for chromosome in mutation_dict[strand]:
for position in mutation_dict[strand][chromosome]:
val = mutation_dict[strand][chromosome][position]
if val < min(all_values):
val = min(all_values)
if val > max(all_values):
val = max(all_values)
normed_dict[strand][chromosome][position] = val/max_value
return normed_dict
def split_by_n(line, n=6):
"""
trims endline, and returns set of chunks of length 6, each of which has whitespace stripped
:param line:
:param n:
:return:
"""
return [line[i:i+n].strip() for i in range(0, len(line), 6)]
rRNA_assignments = {3:{'d':"S.c.18S_rRNA"}, 1:{'A':"S.c.18S_rRNA"},2:{'A':"S.c.25S__rRNA", 'B':"S.c.5S___rRNA", 'C':"S.c.5.8S_rRNA"} , (4,'K'):"S.c.25S__rRNA", (4,'L'):"S.c.5S___rRNA", (4,'M'):"S.c.5.8S_rRNA", (2,'C'):"S.c.5.8S_rRNA"}
def main():
outprefix, bundle1, bundle2, bundle3, bundle4, bundle5, datafile_name = sys.argv[1:8]
bundles = [bundle1, bundle2, bundle3, bundle4, bundle5]
reactivities = mod_utils.unPickle(datafile_name)
for i in range(1,6):
infile = open(bundles[i-1])
outfile = open(outprefix+'_bundle'+str(i)+'.pdb' ,'w')
for line in infile:
if line.startswith('ATOM'):
chain = line[21]
resi = int(line[22:28].strip())
if i in rRNA_assignments and chain in rRNA_assignments[i] and resi in reactivities['+'][rRNA_assignments[i][chain]]:
new_line = '%s%6.3f%s' % (line[:60], reactivities['+'][rRNA_assignments[i][chain]][resi], line[66:])
assert len(line) == len(new_line)
else:
new_line = '%s%6.4f%s' % (line[:60], 0.0, line[66:])
assert len(line) == len(new_line)
elif line.startswith("ANISOU"):
new_line = '' #remove the anisotropic b factors, I don't need them
else:
new_line = line
outfile.write(new_line)
infile.close()
outfile.close()
main() | {
"repo_name": "borisz264/mod_seq",
"path": "unused_scripts/map_onto_rRNA_structure.py",
"copies": "1",
"size": "4996",
"license": "mit",
"hash": -3153490915391695400,
"line_mean": 38.976,
"line_max": 234,
"alpha_frac": 0.5880704564,
"autogenerated": false,
"ratio": 3.2547231270358306,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.43427935834358306,
"avg_score": null,
"num_lines": null
} |
__author__ = 'boris'
"""
I really want to use this mod-seq data to generate something resembling an x-ray exposure of a sequencing gel
inputs:
chromosome: the chromosome to plot from
start: the position to start plotting from
stop: the position to stop plotting
mutations.pkl: from parse_shapemapper_counts2.py, pickled dict of [chromosome][dataset][position] = mutation counts
coverage.pkl: from parse_shapemapper_counts2.py, pickled dict of [chromosome][dataset][position] = coverage counts
datasets: any number of names matching datsets in the mutations and coverage pickles
"""
import mod_utils, math, os
import numpy
import matplotlib.pyplot as plt
plt.rcParams['pdf.fonttype'] = 42 #leaves most text as actual text in PDFs, not outlines
def gaussian(x, mean, variance, scale):
#removed division by math.sqrt(variance*2*math.pi) so that peak height equals mutation rate
return (float(scale) * math.exp(-1*((float(x)-float(mean))**2)/(2*variance)))
def true_gaussian(x, mean, variance, scale):
return (float(scale)/math.sqrt(variance*2*math.pi)) * math.exp(-1*((float(x)-float(mean))**2)/(2*variance))
def generate_single_mutation_rates_dict(chromosome, start, stop, folder, file_names, strip_suffix):
combined_mutation_rates = {}
for file_name in file_names:
dataset_label = file_name.rstrip(strip_suffix)
mutation_rates = mod_utils.unPickle(os.path.join(folder, file_name))
mutation_array = [float(mutation_rates[chromosome][position]) if position in mutation_rates[chromosome] else 0.0 for position in range(start, stop+1)]
combined_mutation_rates[dataset_label] = mutation_array
return combined_mutation_rates
def generate_gaussian_densities(mutation_rates, band_spacing, band_variance):
"""
:param mutation_rates: output of generate_mutation_rates
:param band_spacing: number of positions (pixels) between band centers
:param band_variance: the variance of the guassian representing each band (in positions/pixels)
:return:
"""
band_densities = {}
for dataset in mutation_rates:
print dataset
#center of first band will be at band_spacing/2 (zero-indexed, so wiht a spacing of 20, it will be position 10,
# the 11th entry in the array)
#center of each subsequent band will be band_spacing+1 units from the previous 1
summed_density_array = numpy.array([0.0]*(len(mutation_rates[dataset])*(band_spacing+1)))
for position in range(len(mutation_rates[dataset])):
band_position = (band_spacing/2) + (band_spacing+1)*position
band_intensity = mutation_rates[dataset][position]
#compute the contribution, at each position in the area of interest, from this band
temp_array = numpy.array([gaussian(x, band_position, band_variance, band_intensity) for x in range(len(summed_density_array))])
#temp_array = numpy.array([gaussian(x, band_position, math.sqrt(band_intensity)*band_variance, band_intensity) for x in range(len(summed_density_array))])
summed_density_array = summed_density_array + temp_array
band_densities[dataset] = summed_density_array
return band_densities
def plot_density_lines(dataset_names, gaussian_densities, band_spacing, start, stop, chromosome):
fig = plt.figure()
plot = fig.add_subplot(111)
color_index = 0
for dataset in dataset_names:
plot.plot(gaussian_densities[dataset], color = mod_utils.colors[color_index], label= dataset)
color_index +=1
lg=plt.legend(loc=2,prop={'size':10}, labelspacing=0.2)
lg.draw_frame(False)
plot.set_xlabel('nt position in %s' % chromosome)
plot.set_ylabel('band intensity')
plot.set_xticks([(band_spacing/2) + (band_spacing+1)*position for position in range(1+stop-start)])
plot.set_xticklabels(range(start, stop+1))
plt.xticks(rotation=90)
plt.show()
def main():
'''
chromosome, start, stop, mutations, coverage = sys.argv[1:6]
start = int(start)
stop = int(stop)
dataset_names = sys.argv[6:]
'''
chromosome, start, stop, mutation_rates_folder = 'S.c.25S__rRNA', 2740, 2800, '/Users/boris/Green_Lab/Book_2/2.47/analysis/pickles/raw'
file_names = ['80S_no_DMS_mutation_rates.pkl', '80S_mutation_rates.pkl', '80S_10uM_CHX_mutation_rates.pkl', '80S_50uM_CHX_mutation_rates.pkl', '80S_1000uM_CHX_mutation_rates.pkl']
strip_suffix = '_mutation_rates.pkl'
dataset_labels = [file_name.rstrip(strip_suffix) for file_name in file_names]
mutation_rates_dict = generate_single_mutation_rates_dict(chromosome, start, stop, mutation_rates_folder, file_names, strip_suffix)
print mutation_rates_dict.keys()
band_spacing = 200
#band_variance = 50000.
band_variance = 2000.
gaussian_densities = generate_gaussian_densities(mutation_rates_dict, band_spacing, band_variance )
plot_density_lines(dataset_labels, gaussian_densities, band_spacing, start, stop, chromosome)
main()
| {
"repo_name": "borisz264/mod_seq",
"path": "gel_drawing/simulate_gel.py",
"copies": "1",
"size": "5018",
"license": "mit",
"hash": 2132368530738345700,
"line_mean": 47.7184466019,
"line_max": 183,
"alpha_frac": 0.702471104,
"autogenerated": false,
"ratio": 3.463077984817115,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9579586863317986,
"avg_score": 0.017192445099825756,
"num_lines": 103
} |
__author__ = 'boris'
"""
5'e end data is a pickled dict of form srt_dict[chrom][position] = counts at position
take the 5' end data from count_reads_and_mismatches.py, as well as any number of files output by
compute_true_positive_negative.py
and compute:
1) 90% windorize the input data (All data above 95th percentile set to 95th percentile)
2) normalize to highest position in rRNA (should just stick to the rRNA of interest, which will be 18S for my initial test)
3) slide a cutoff from 0 to 1 in ~10,000 steps, computing % of true positives and true negatives called positive at each step
4) plot these two percentages against each other for each step, also output these values as a spreadsheet
also plot y=x for reference
"""
import sys, mod_utils, os
import numpy
from scipy.stats.mstats import winsorize
import matplotlib.pyplot as plt
plt.rcParams['pdf.fonttype'] = 42 #leaves most text as actual text in PDFs, not outlines
from collections import defaultdict
def winsorize_norm_chromosome_data(mut_density, chromosome, genome_dict, nucs_to_count, to_winsorize = False, low = 0, high = 0.95):
"""
:param read_5p_ends:
:param chromosome:
:param strand:
:param genome_dict:
:param nucs_to_count:
:param low:
:param high:
:return: an array (now zero-indexed from 1-indexed) of densities for the given chromosome on the given strand, winsorized, and only for the given nucleotides
"""
max_position = max(mut_density[chromosome].keys())
density_array =numpy.array([0.0] * max_position)
for position in mut_density[chromosome].keys():
if genome_dict[chromosome][position-1] in nucs_to_count:
density_array[position-1] = mut_density[chromosome][position]
if to_winsorize:
winsorize(density_array, limits = (low, 1-high), inplace = True)
normed_array = density_array/float(max(density_array))
return normed_array
def get_tp_tn(tp_tn_file):
TP = set()
TN = set()
f = open(tp_tn_file)
for line in f:
ll= line.strip('\n').split('\t')
if ll[2] == 'TP':
TP.add(int(ll[0]))
if ll[2] =='TN':
TN.add(int(ll[0]))
f.close()
return TP, TN
def call_positives(density_array, chromosome, genome_dict, nucs_to_count, cutoff):
"""
:param density_array:
:return:a set of called positive positions
I've reverted these to 1-indexed to match the TP and TN calls from the structures
"""
positives = set()
for i in range(len(density_array)):
if genome_dict[chromosome][i] in nucs_to_count:
if density_array[i] >= cutoff:
positives.add(i+1)#adding 1 not necessary for RT stops, since the modified nucleotide is the one 1 upstream of the RT stop!!!
return positives
def plot_ROC_curves(roc_curves, title, out_prefix):
fig = plt.figure(figsize=(8,8))
plot = fig.add_subplot(111)#first a pie chart of mutated nts
colormap = plt.get_cmap('spectral')
color_index = 0
for name in sorted(roc_curves.keys()):
x, y = roc_curves[name]
area_under_curve = numpy.trapz(numpy.array(y[::-1])/100., x=numpy.array(x[::-1])/100.)
plot.plot(x, y, lw =2, label = '%s %.3f' % (name, area_under_curve), color = colormap(color_index/float(len(roc_curves))))
color_index +=1
plot.plot(numpy.arange(0,100,0.1), numpy.arange(0,100,0.1), lw =1, ls = 'dashed', color = mod_utils.black, label = 'y=x')
plot.set_xlabel('False positive rate (%) (100-specificity)')
plot.set_ylabel('True positive rate (%) (sensitivity)')
plot.set_title(title)
lg=plt.legend(loc=4,prop={'size':10}, labelspacing=0.2)
lg.draw_frame(False)
plt.savefig(out_prefix + '.pdf', transparent='True', format='pdf')
plt.clf()
def pie_read_5p_ends(read_5p_ends, genome_dict, out_prefix):
nuc_counts = defaultdict(int)
for chromosome in read_5p_ends['+']:
for position in read_5p_ends['+'][chromosome]:
if position-2 > 0 :
nuc = genome_dict[chromosome][position-1]
nuc_counts[nuc] += read_5p_ends['+'][chromosome][position]
fig = plt.figure(figsize=(8,8))
plot = fig.add_subplot(111)#first a pie chart of mutated nts
labels = sorted(nuc_counts.keys())
sizes = [nuc_counts[nt] for nt in labels]
plot.pie(sizes, labels = labels, colors = mod_utils.rainbow)
plot.set_title('nt exactly at read 5p ends across rRNA')
plt.savefig(out_prefix + '_nt_5p_ends.pdf', transparent='True', format='pdf')
plt.clf()
def main():
tp_tn_annotations, genome_fasta, outprefix = sys.argv[1:4]
density_files = sys.argv[4:]
sample_names = [os.path.basename(filename).split('_back_')[0] for filename in density_files]
mutation_densities = [mod_utils.unPickle(pickled_density) for pickled_density in density_files]
genome_dict = mod_utils.convertFastaToDict(genome_fasta)
normed_density_arrays = [winsorize_norm_chromosome_data(mutation_density, 'S.c.25S__rRNA', genome_dict, 'AC') for mutation_density in mutation_densities]
real_tp, real_tn = get_tp_tn(tp_tn_annotations)
roc_curves = {}
for sample_name in sample_names:
roc_curves[sample_name] = [[],[]]#x and y value arrays for each
stepsize = 0.0001
for cutoff in numpy.arange(0.0,1.+5*stepsize, stepsize):
for i in range(len(sample_names)):
#the fasta file should be the EXACT one used for the pipeline, and the chromosome name below should match
# the one in the FASTA file exactly
called_p = call_positives(normed_density_arrays[i], 'S.c.25S__rRNA', genome_dict, 'AC', cutoff)
num_tp_called = len(called_p.intersection(real_tp))#how many true positives called at this cutoff
num_fp_called = len(called_p.intersection(real_tn))#how many fp positives called at this cutoff
roc_curves[sample_names[i]][1].append(100.*num_tp_called/float(len(real_tp)))#TP rate on y axis
roc_curves[sample_names[i]][0].append(100.*num_fp_called/float(len(real_tn)))#FP rate on x axis
plot_ROC_curves(roc_curves, 'S.c.25S__rRNA', outprefix)
#pie_read_5p_ends(read_5p_ends, genome_dict, outprefix)
if __name__ == '__main__':
main() | {
"repo_name": "borisz264/mod_seq",
"path": "structure_ROC_curves/roc_curves_compare_datasets_shapemapper.py",
"copies": "1",
"size": "6279",
"license": "mit",
"hash": 2117621924518922200,
"line_mean": 44.1798561151,
"line_max": 161,
"alpha_frac": 0.6582258321,
"autogenerated": false,
"ratio": 3.24831867563373,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9354269185484181,
"avg_score": 0.010455064449909686,
"num_lines": 139
} |
__author__ = 'boris'
"""
takes:
all_counts - pickled dict of mutation counts, all_counts[rRNA_name][sample_name] = counts_table
all_Depths - pickled dict of coverage counts , all_depths[rRNA_name][sample_name] = depth_table
min_mutations: if a position has less coverage than less mutations than this across both datasets, the subtracted total will be set to zero, and the ratio to 1
output_prefix
comparisons: any number of sample,control name pairs
makes for each comparison_pair:
a dict of subtraction-normed mutation rates
a dict of variance for subtracted rates
a dict of division-normed mutation rates
a dict of variance for division-normed rates
"""
import sys, math, mod_utils
from collections import defaultdict
def write_out_counts(subtracted_rates, subtraction_errors, divided_rates, division_errors, rRNA, output_filename):
f = open(output_filename, 'w')
f.write('position\tsubtracted\tsub error\tdivided\tdiv error\n')
for position in sorted(subtracted_rates[rRNA]):
line = '%d\t%f\t%f\t%f\t%f\n' % (position, subtracted_rates[rRNA][position], subtraction_errors[rRNA][position], divided_rates[rRNA][position],division_errors[rRNA][position])
f.write(line)
f.close()
def standard_error(mutations, coverage):
return math.sqrt(float(mutations))/float(coverage)
def subtraction_norm(all_counts, all_depths, min_mutations, comparison):
sample = comparison[0]
control = comparison[1]
normalized_rates = defaultdict(dict)
normalized_errors = defaultdict(dict)
for rRNA_name in all_counts:
for position in all_counts[rRNA_name][sample]:
if all_counts[rRNA_name][sample][position] >= min_mutations and all_counts[rRNA_name][control][position] >= min_mutations:
sample_ratio = float(all_counts[rRNA_name][sample][position])/float(all_depths[rRNA_name][sample][position])
sample_error = standard_error(all_counts[rRNA_name][sample][position], all_depths[rRNA_name][sample][position])
control_ratio = float(all_counts[rRNA_name][control][position])/float(all_depths[rRNA_name][control][position])
control_error = standard_error(all_counts[rRNA_name][control][position], all_depths[rRNA_name][control][position])
normalized_rates[rRNA_name][position] = sample_ratio-control_ratio
normalized_errors[rRNA_name][position] = math.sqrt((sample_error**2)+(control_error**2))
else:
normalized_rates[rRNA_name][position] = 0
normalized_errors[rRNA_name][position] = 0
return normalized_rates, normalized_errors
def division_norm(all_counts, all_depths, min_mutations, comparison):
sample = comparison[0]
control = comparison[1]
normalized_rates = defaultdict(dict)
normalized_errors = defaultdict(dict)
for rRNA_name in all_counts:
for position in all_counts[rRNA_name][sample]:
if all_counts[rRNA_name][sample][position] >= min_mutations and all_counts[rRNA_name][control][position] >= min_mutations:
sample_ratio = float(all_counts[rRNA_name][sample][position])/float(all_depths[rRNA_name][sample][position])
sample_error = standard_error(all_counts[rRNA_name][sample][position], all_depths[rRNA_name][sample][position])
control_ratio = float(all_counts[rRNA_name][control][position])/float(all_depths[rRNA_name][control][position])
control_error = standard_error(all_counts[rRNA_name][control][position], all_depths[rRNA_name][control][position])
normalized_rates[rRNA_name][position] = math.log(sample_ratio/control_ratio, 2)
normalized_errors[rRNA_name][position] = ((sample_ratio/control_ratio)*math.sqrt((sample_error/sample_ratio)**2+(control_error/control_ratio)**2))/((sample_ratio/control_ratio)*math.log(2))
#this is a standard error propogation formula
else:
normalized_rates[rRNA_name][position] = 0
normalized_errors[rRNA_name][position] = 0
return normalized_rates, normalized_errors
def main():
all_counts_file, all_depths_file, min_mutations, output_prefix = sys.argv[1:5]
min_mutations = int(min_mutations)
all_counts = mod_utils.unPickle(all_counts_file)
all_depths = mod_utils.unPickle(all_depths_file)
comparisons = (pair.split(',') for pair in sys.argv[5:])
for comparison in comparisons:
subtracted_rates, subtraction_errors = subtraction_norm(all_counts, all_depths, min_mutations, comparison)
divided_rates, division_errors = division_norm(all_counts, all_depths, min_mutations, comparison)
mod_utils.makePickle(subtracted_rates, '%s_%s_%s_sub_norm.pkl' % (output_prefix, comparison[0], comparison[1]))
mod_utils.makePickle(subtraction_errors, '%s_%s_%s_sub_err.pkl' % (output_prefix, comparison[0], comparison[1]))
mod_utils.makePickle(divided_rates, '%s_%s_%s_div_norm.pkl' % (output_prefix, comparison[0], comparison[1]))
mod_utils.makePickle(division_errors, '%s_%s_%s_div_err.pkl' % (output_prefix, comparison[0], comparison[1]))
for rRNA in subtracted_rates:
write_out_counts(subtracted_rates, subtraction_errors, divided_rates, division_errors, rRNA, '%s_%s_%s_%s.txt' % (output_prefix, comparison[0], comparison[1], rRNA))
main() | {
"repo_name": "borisz264/mod_seq",
"path": "unused_scripts/subtract_shapemapper_counts.py",
"copies": "1",
"size": "5425",
"license": "mit",
"hash": -5226015900884519000,
"line_mean": 55.5208333333,
"line_max": 205,
"alpha_frac": 0.6849769585,
"autogenerated": false,
"ratio": 3.522727272727273,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47077042312272727,
"avg_score": null,
"num_lines": null
} |
__author__ = 'boris'
"""
THIS IS AN OLD SCRIPT, use the _shapemapper.py version instead
5'e end data is a pickled dict of form srt_dict[strand][chrom][position] = counts at position
take the 5' end data from count_reads_and_mismatches.py, as well as any number of files output by
compute_true_positive_negative.py
and compute:
1) 90% windorize the input data (All data above 95th percentile set to 95th percentile)
2) normalize to highest position in rRNA (should just stick to the rRNA of interest, which will be 18S for my initial test)
3) slide a cutoff from 0 to 1 in ~10,000 steps, computing % of true positives and true negatives called positive at each step
4) plot these two percentages against each other for each step, also output these values as a spreadsheet
also plot y=x for reference
"""
import sys, mod_utils, os
import numpy
from scipy.stats.mstats import winsorize
import matplotlib.pyplot as plt
plt.rcParams['pdf.fonttype'] = 42 #leaves most text as actual text in PDFs, not outlines
from collections import defaultdict
def winsorize_norm_chromosome_data(mut_density, chromosome, strand, genome_dict, nucs_to_count, to_winsorize = False, low = 0, high = 0.95):
"""
:param read_5p_ends:
:param chromosome:
:param strand:
:param genome_dict:
:param nucs_to_count:
:param low:
:param high:
:return: an array (now zero-indexed from 1-indexed) of densities for the given chromosome on the given strand, winsorized, and only for the given nucleotides
"""
max_position = max(mut_density[strand][chromosome].keys())
density_array =numpy.array([0.0] * max_position)
for position in mut_density[strand][chromosome].keys():
if genome_dict[chromosome][position-1] in nucs_to_count:
density_array[position-1] = mut_density[strand][chromosome][position]
if to_winsorize:
winsorize(density_array, limits = (low, 1-high), inplace = True)
normed_array = density_array/float(max(density_array))
return normed_array
def get_tp_tn(tp_tn_file):
TP = set()
TN = set()
f = open(tp_tn_file)
for line in f:
ll= line.strip('\n').split('\t')
if ll[2] == 'TP':
TP.add(int(ll[0]))
if ll[2] =='TN':
TN.add(int(ll[0]))
f.close()
return TP, TN
def call_positives(density_array, chromosome, strand, genome_dict, nucs_to_count, cutoff):
"""
:param density_array:
:return:a set of called positive positions
I've reverted these to 1-indexed to match the TP and TN calls from the structures
"""
positives = set()
for i in range(len(density_array)):
if genome_dict[chromosome][i] in nucs_to_count:
if density_array[i] >= cutoff:
positives.add(i+1)#adding 1 not necessary for RT stops, since the modified nucleotide is the one 1 upstream of the RT stop!!!
return positives
def plot_ROC_curves(roc_curves, out_prefix):
fig = plt.figure(figsize=(8,8))
plot = fig.add_subplot(111)#first a pie chart of mutated nts
color_index = 0
for name in roc_curves:
x, y = roc_curves[name]
plot.plot(x, y, lw =2, label = name, color = mod_utils.rainbow[color_index])
color_index +=1
plot.plot(x, x, lw =1, ls = 'dashed', color = mod_utils.rainbow[color_index], label = 'y=x')
plot.set_xlabel('False positive rate (%) (100-specificity)')
plot.set_ylabel('True positive rate (%) (sensitivity)')
lg=plt.legend(loc=2,prop={'size':10}, labelspacing=0.2)
lg.draw_frame(False)
plt.savefig(out_prefix + '.pdf', transparent='True', format='pdf')
plt.clf()
def pie_read_5p_ends(read_5p_ends, genome_dict, out_prefix):
nuc_counts = defaultdict(int)
for chromosome in read_5p_ends['+']:
for position in read_5p_ends['+'][chromosome]:
if position-2 > 0 :
nuc = genome_dict[chromosome][position-1]
nuc_counts[nuc] += read_5p_ends['+'][chromosome][position]
fig = plt.figure(figsize=(8,8))
plot = fig.add_subplot(111)#first a pie chart of mutated nts
labels = sorted(nuc_counts.keys())
sizes = [nuc_counts[nt] for nt in labels]
plot.pie(sizes, labels = labels, colors = mod_utils.rainbow)
plot.set_title('nt exactly at read 5p ends across rRNA')
plt.savefig(out_prefix + '_nt_5p_ends.pdf', transparent='True', format='pdf')
plt.clf()
def main():
tp_tn_annotations, genome_fasta, outprefix = sys.argv[1:4]
density_files = sys.argv[4:]
sample_names = [os.path.basename(filename) for filename in density_files]
mutation_densities = [mod_utils.unPickle(pickled_density) for pickled_density in density_files]
genome_dict = mod_utils.convertFastaToDict(genome_fasta)
normed_density_arrays = [winsorize_norm_chromosome_data(mutation_density, 'S.c.18S_rRNA', '+', genome_dict, 'ACTG') for mutation_density in mutation_densities]
real_tp, real_tn = get_tp_tn(tp_tn_annotations)
roc_curves = {}
for sample_name in sample_names:
roc_curves[sample_name] = [[],[]]#x and y value arrays for each
stepsize = 0.0001
for cutoff in numpy.arange(0,1.+5*stepsize, stepsize):
for i in range(len(sample_names)):
called_p = call_positives(normed_density_arrays[i], 'S.c.18S_rRNA', '+', genome_dict, 'AC', cutoff)
num_tp_called = len(called_p.intersection(real_tp))#how many true positives called at this cutoff
num_fp_called = len(called_p.intersection(real_tn))#how many fp positives called at this cutoff
roc_curves[sample_names[i]][1].append(100.*num_tp_called/float(len(real_tp)))#TP rate on y axis
roc_curves[sample_names[i]][0].append(100.*num_fp_called/float(len(real_tn)))#FP rate on x axis
plot_ROC_curves(roc_curves, outprefix)
#pie_read_5p_ends(read_5p_ends, genome_dict, outprefix)
if __name__ == '__main__':
main() | {
"repo_name": "borisz264/mod_seq",
"path": "structure_ROC_curves/roc_curves_compare_datasets.py",
"copies": "1",
"size": "5936",
"license": "mit",
"hash": 419200575673032770,
"line_mean": 42.9777777778,
"line_max": 163,
"alpha_frac": 0.661893531,
"autogenerated": false,
"ratio": 3.2615384615384615,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.44234319925384613,
"avg_score": null,
"num_lines": null
} |
__author__ = 'boris'
"""
THIS IS FOR TROUBLESHOOTING AND COMPARING DIFFERENT TRUE POSITIVE AND TRUE NEGATIVE ANNOTATIONS
5'e end data is a pickled dict of form srt_dict[strand][chrom][position] = counts at position
take the 5' end data from count_reads_and_mismatches.py, as well as any number of files output by
compute_true_positive_negative.py
and compute:
1) 90% windorize the input data (All data above 95th percentile set to 95th percentile)
2) normalize to highest position in rRNA (should just stick to the rRNA of interest, which will be 18S for my initial test)
3) slide a cutoff from 0 to 1 in ~10,000 steps, computing % of true positives and true negatives called positive at each step
4) plot these two percentages against each other for each step, also output these values as a spreadsheet
also plot y=x for reference
"""
import sys, mod_utils, os
import numpy
from scipy.stats.mstats import winsorize
import matplotlib.pyplot as plt
plt.rcParams['pdf.fonttype'] = 42 #leaves most text as actual text in PDFs, not outlines
from collections import defaultdict
def winsorize_norm_chromosome_data(read_5p_ends, chromosome, strand, genome_dict, nucs_to_count, to_winsorize = True, low = 0, high = 0.95):
"""
:param read_5p_ends:
:param chromosome:
:param strand:
:param genome_dict:
:param nucs_to_count:
:param low:
:param high:
:return: an array (now zero-indexed from 1-indexed) of densities for the given chromosome on the given strand, winsorized, and only for the given nucleotides
"""
max_position = max(read_5p_ends[strand][chromosome].keys())
density_array =numpy.array([0] * max_position)
for position in read_5p_ends[strand][chromosome].keys():
if genome_dict[chromosome][position-1] in nucs_to_count:
density_array[position-1] = read_5p_ends[strand][chromosome][position]
if to_winsorize:
winsorize(density_array, limits = (low, 1-high), inplace = True)
normed_array = density_array/float(max(density_array))
return normed_array
def get_tp_tn(tp_tn_file):
TP = set()
TN = set()
f = open(tp_tn_file)
for line in f:
ll= line.strip('\n').split('\t')
if ll[2] == 'TP':
TP.add(int(ll[0]))
if ll[2] =='TN':
TN.add(int(ll[0]))
f.close()
return TP, TN
def call_positives(density_array, chromosome, strand, genome_dict, nucs_to_count, cutoff):
"""
:param density_array:
:return:a set of called positive positions
I've reverted these to 1-indexed to match the TP and TN calls from the structures
"""
positives = set()
for i in range(len(density_array)):
if genome_dict[chromosome][i-1] in nucs_to_count:
if density_array[i] >= cutoff:
positives.add(i)#adding 1 not necessary, since the modified nucleotide is the one 1 upstream of the RT stop!!!
return positives
def plot_ROC_curves(roc_curves, out_prefix):
fig = plt.figure(figsize=(8,8))
plot = fig.add_subplot(111)#first a pie chart of mutated nts
color_index = 0
for name in roc_curves:
x, y = roc_curves[name]
plot.plot(x, y, lw =2, label = name, color = mod_utils.rainbow[color_index])
color_index +=1
plot.plot(x, x, lw =1, ls = 'dashed', color = mod_utils.rainbow[color_index], label = 'y=x')
plot.set_xlabel('False positive rate (%) (100-specificity)')
plot.set_ylabel('True positive rate (%) (sensitivity)')
lg=plt.legend(loc=2,prop={'size':10}, labelspacing=0.2)
lg.draw_frame(False)
plt.savefig(out_prefix + '.pdf', transparent='True', format='pdf')
plt.clf()
def pie_read_5p_ends(read_5p_ends, genome_dict, out_prefix):
nuc_counts = defaultdict(int)
for chromosome in read_5p_ends['+']:
for position in read_5p_ends['+'][chromosome]:
if position-2 > 0 :
nuc = genome_dict[chromosome][position-1]
nuc_counts[nuc] += read_5p_ends['+'][chromosome][position]
fig = plt.figure(figsize=(8,8))
plot = fig.add_subplot(111)#first a pie chart of mutated nts
labels = sorted(nuc_counts.keys())
sizes = [nuc_counts[nt] for nt in labels]
plot.pie(sizes, labels = labels, colors = mod_utils.rainbow)
plot.set_title('nt exactly at read 5p ends across rRNA')
plt.savefig(out_prefix + '_nt_5p_ends.pdf', transparent='True', format='pdf')
plt.clf()
def main():
read_5p_ends_file, genome_fasta, outprefix = sys.argv[1:4]
tp_tn_annotations = sys.argv[4:]#true positive and true negative annotations
genome_dict = mod_utils.convertFastaToDict(genome_fasta)
read_5p_ends = mod_utils.unPickle(read_5p_ends_file)
normed_density_array = winsorize_norm_chromosome_data(read_5p_ends, 'S.c.18S_rRNA', '+', genome_dict, 'ACTG')
real_tp_tn_data = []
for filename in tp_tn_annotations:
real_tp, real_tn = get_tp_tn(filename)
real_tp_tn_data.append((os.path.basename(filename), real_tp, real_tn))
roc_curves = {}
for entry in real_tp_tn_data:
roc_curves[entry[0]] = [[],[]]#x and y value arrays for each
stepsize = 0.0001
for cutoff in numpy.arange(0,1.+5*stepsize, stepsize):
called_p = call_positives(normed_density_array, 'S.c.18S_rRNA', '+', genome_dict, 'AC', cutoff)
for entry in real_tp_tn_data:
#print called_p.intersection(entry[1])
num_tp_called = len(called_p.intersection(entry[1]))#how many true positives called at this cutoff
num_fp_called = len(called_p.intersection(entry[2]))#how many fp positives called at this cutoff
roc_curves[entry[0]][0].append(100.*num_fp_called/float(len(entry[2])))#FP rate on x axis
roc_curves[entry[0]][1].append(100.*num_tp_called/float(len(entry[1])))#TP rate on y axis
plot_ROC_curves(roc_curves, outprefix)
#pie_read_5p_ends(read_5p_ends, genome_dict, outprefix)
if __name__ == '__main__':
main() | {
"repo_name": "borisz264/mod_seq",
"path": "structure_ROC_curves/roc_curves_compare_annotations.py",
"copies": "1",
"size": "5995",
"license": "mit",
"hash": -4845367873214606000,
"line_mean": 42.1366906475,
"line_max": 161,
"alpha_frac": 0.657381151,
"autogenerated": false,
"ratio": 3.202457264957265,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.43598384159572645,
"avg_score": null,
"num_lines": null
} |
__author__ = 'boris zinshteyn'
"""
Intended for processing of 80s monosome-seq data from defined RNA pools
Based on Alex Robertson's original RBNS pipeline, available on github
"""
import matplotlib.pyplot as plt
plt.rcParams['pdf.fonttype'] = 42 #leaves most text as actual text in PDFs, not outlines
import os
import argparse
import subprocess
import ms_settings
import ms_utils
import ms_lib
import ms_qc
import ms_plotting
from collections import defaultdict
import numpy as np
import scipy.stats as stats
class mse:
def __init__(self, settings, threads):
self.threads = threads
self.settings = settings
self.remove_adaptor()
self.trim_reference_pool_fasta()
self.build_bowtie_index()
self.map_reads()
self.initialize_libs()
def initialize_libs(self):
self.settings.write_to_log('initializing libraries, counting reads')
ms_utils.make_dir(self.rdir_path('sequence_counts'))
self.libs = []
ms_utils.parmap(lambda lib_settings: ms_lib.initialize_pool_sequence_mappings(self.settings, lib_settings),
self.settings.iter_lib_settings(), nprocs=self.threads)
map(lambda lib_settings: self.initialize_lib(lib_settings), self.settings.iter_lib_settings())
self.settings.write_to_log('initializing libraries, counting reads, done')
self.monosome_libs = [self.find_lib_by_sample_name(sample_name) for
sample_name in self.settings.get_property('monosome_libraries')]
self.mrnp_libs = [self.find_lib_by_sample_name(sample_name) for
sample_name in self.settings.get_property('mrnp_libraries')]
self.total_libs = [self.find_lib_by_sample_name(sample_name) for
sample_name in self.settings.get_property('total_libraries')]
self.input_libs = [self.find_lib_by_sample_name(sample_name) for
sample_name in self.settings.get_property('total_libraries')]
def find_lib_by_sample_name(self, sample_name):
for lib in self.libs:
if lib.lib_settings.sample_name == sample_name:
return lib
assert False #if this triggers, your settings file is broken.
def initialize_lib(self, lib_settings):
lib = ms_lib.ms_Lib(self.settings, lib_settings)
self.libs.append(lib)
def needs_calculation(self, lib_settings, count_type, k):
if self.settings.get_force_recount(count_type):
return True
return not lib_settings.counts_exist(count_type, k)
def make_tables(self):
ms_utils.make_dir(self.rdir_path('tables'))
self.make_counts_table()
self.make_counts_table(fractional=True)
self.make_monosome_recruitment_table()
self.write_sequence_subset(0, read_cutoff=128)
self.write_sequence_subset(0.8, read_cutoff=128)
self.write_sequence_subset(0.7, read_cutoff=128)
for anno_filename in self.settings.get_property('matched_set_annotations'):
self.make_matched_recruitment_change_table(anno_filename,
read_cutoff=self.settings.get_property('comparison_read_cutoff'))
def make_plots(self):
ms_utils.make_dir(self.rdir_path('plots'))
#ms_plotting.all_library_rpm_scatter(self)
#ms_plotting.monosome_over_mrnp_reproducibility(self)
#ms_plotting.monosome_over_total_reproducibility(self)
#ms_plotting.monosome_over_mrnp_plus_monosome_reproducibility(self)
for anno_filename in self.settings.get_property('matched_set_annotations'):
ms_plotting.plot_recruitment_violins(self, anno_filename,
read_cutoff=self.settings.get_property('comparison_read_cutoff'))
'''
ms_plotting.recruitment_change_rank_value_plot_static(self, anno_filename,
read_cutoff=self.settings.get_property('comparison_read_cutoff'))
ms_plotting.reverse_recruitment_change_rank_value_plot_static(self, anno_filename,
read_cutoff=self.settings.get_property('comparison_read_cutoff'))
if self.settings.get_property('make_interactive_plots'):
ms_plotting.recruitment_change_rank_value_plot_interactive(self, anno_filename,
read_cutoff=self.settings.get_property('comparison_read_cutoff'))
ms_plotting.recruitment_fold_change_rank_value_plot_interactive(self, anno_filename,
read_cutoff=self.settings.get_property(
'comparison_read_cutoff'))
'''
def remove_adaptor(self):
if not self.settings.get_property('force_retrim'):
for lib_settings in self.settings.iter_lib_settings():
if not lib_settings.adaptorless_reads_exist():
break
else:
return
if self.settings.get_property('trim_adaptor'):
ms_utils.make_dir(self.rdir_path('adaptor_removed'))
ms_utils.parmap(lambda lib_setting: self.remove_adaptor_one_lib(lib_setting), self.settings.iter_lib_settings(), nprocs = self.threads)
def remove_adaptor_one_lib(self, lib_settings):
lib_settings.write_to_log('adaptor trimming')
"""
-a specifies the 3' adaptor to trim from the forawrd read (read1)
-G specifies the 5' adaptor to trim from the reverse read (read2)
-o is the read1 output file
-p is the read2 output file
"""
if not self.settings.get_property('read2_5p_adaptor_sequence').strip()=='':
command_to_run = 'cutadapt -a %s -G %s --overlap 5 -u %d -U %d -q %d --trim-n --minimum-length %d --pair-filter=both -o %s -p %s %s %s 1>>%s 2>>%s' % (
self.settings.get_property('read1_3p_adaptor_sequence'), self.settings.get_property('read2_5p_adaptor_sequence'),
self.settings.get_property('read1_5p_bases_to_trim'), self.settings.get_property('read2_5p_bases_to_trim'),
self.settings.get_property('quality_cutoff'), self.settings.get_property('min_post_adaptor_length'),
lib_settings.get_adaptor_trimmed_reads()[0], lib_settings.get_adaptor_trimmed_reads()[1],
lib_settings.get_paired_fastq_gz_files()[0], lib_settings.get_paired_fastq_gz_files()[1],
lib_settings.get_log(), lib_settings.get_log())
else:
command_to_run = 'cutadapt -a %s --overlap 5 -u %d -U %d -q %d --trim-n --minimum-length %d --pair-filter=both -o %s -p %s %s %s 1>>%s 2>>%s' % (
self.settings.get_property('read1_3p_adaptor_sequence'),
self.settings.get_property('read1_5p_bases_to_trim'), self.settings.get_property('read2_5p_bases_to_trim'),
self.settings.get_property('quality_cutoff'), self.settings.get_property('min_post_adaptor_length'),
lib_settings.get_adaptor_trimmed_reads()[0], lib_settings.get_adaptor_trimmed_reads()[1],
lib_settings.get_paired_fastq_gz_files()[0], lib_settings.get_paired_fastq_gz_files()[1],
lib_settings.get_log(), lib_settings.get_log())
subprocess.Popen(command_to_run, shell=True).wait()
lib_settings.write_to_log('adaptor trimming done')
def build_bowtie_index(self):
"""
builds a bowtie 2 index from the input fasta file
recommend including barcode+PCR sequences just in case of some no-insert amplicons
"""
self.settings.write_to_log('building bowtie index')
if self.settings.get_property('force_index_rebuild') or not self.settings.bowtie_index_exists():
ms_utils.make_dir(self.rdir_path('bowtie_indices'))
index = self.settings.get_bowtie_index()
subprocess.Popen('bowtie2-build -f --offrate 0 %s %s 1>>%s 2>>%s' % (self.settings.get_trimmed_pool_fasta(),
self.settings.get_bowtie_index(), self.settings.get_log()+'.bwt',
self.settings.get_log()+'.bwt'), shell=True).wait()
self.settings.write_to_log('building bowtie index complete')
def trim_reference_pool_fasta(self):
'''
Trims the reference sequences to the length of the trimmed reads + a buffer
'''
trim_5p = self.settings.get_property('pool_5p_bases_to_trim') #nucleotides to cut from 5' end
trim_3p = self.settings.get_property('pool_3p_bases_to_trim') #nucleotides to cut from 3' end
f = open(self.settings.get_property('pool_fasta'))
g = open(self.settings.get_trimmed_pool_fasta(), 'w')
for line in f:
if not line.strip() == '' and not line.startswith('#'):#ignore empty lines and commented out lines
if line.startswith('>'):#> marks the start of a new sequence
g.write(line)
else:
g.write(self.settings.get_property('pool_prepend')+line.strip()[trim_5p:len(line.strip())-trim_3p]+self.settings.get_property('pool_append')+'\n')
f.close()
g.close()
def map_reads(self):
"""
map all reads using bowtie
:return:
"""
self.settings.write_to_log('mapping reads')
if not self.settings.get_property('force_remapping'):
for lib_settings in self.settings.iter_lib_settings():
if not lib_settings.mapped_reads_exist():
break
else:
return
ms_utils.make_dir(self.rdir_path('mapped_reads'))
ms_utils.make_dir(self.rdir_path('mapping_stats'))
ms_utils.make_dir(self.rdir_path('unmapped_reads'))
ms_utils.parmap(lambda lib_setting: self.map_one_library(lib_setting), self.settings.iter_lib_settings(),
nprocs = self.threads)
self.settings.write_to_log( 'finished mapping reads')
def map_one_library(self, lib_settings):
lib_settings.write_to_log('mapping_reads')
subprocess.Popen('bowtie2 -q --very-sensitive-local --norc --no-mixed --no-overlap --no-discordant -t -x %s -p %d -1 %s -2 %s --un-conc-gz %s -S %s 1>> %s 2>>%s' % (self.settings.get_bowtie_index(), self.threads,
lib_settings.get_adaptor_trimmed_reads()[0], lib_settings.get_adaptor_trimmed_reads()[1], lib_settings.get_unmappable_reads_prefix(), lib_settings.get_mapped_reads_sam(),
lib_settings.get_log(), lib_settings.get_pool_mapping_stats()), shell=True).wait()
#subprocess.Popen('samtools view -b -h -o %s %s 1>> %s 2>> %s' % (lib_settings.get_mapped_reads(), lib_settings.get_mapped_reads_sam(), lib_settings.get_log(), lib_settings.get_log()), shell=True).wait()
#also, sort bam file, and make an index
#samtools view -uS myfile.sam | samtools sort - myfile.sorted
subprocess.Popen('samtools view -uS %s | samtools sort - %s.temp_sorted 1>>%s 2>>%s' % (lib_settings.get_mapped_reads_sam(), lib_settings.get_mapped_reads_sam(),
lib_settings.get_log(), lib_settings.get_log()), shell=True).wait()
#subprocess.Popen('samtools sort %s %s.temp_sorted 1>>%s 2>>%s' % (lib_settings.get_mapped_reads_sam(), lib_settings.get_mapped_reads_sam(),
# lib_settings.get_log(), lib_settings.get_log()), shell=True).wait()
subprocess.Popen('mv %s.temp_sorted.bam %s' % (lib_settings.get_mapped_reads_sam(),
lib_settings.get_mapped_reads()), shell = True).wait()
subprocess.Popen('samtools index %s' % (lib_settings.get_mapped_reads()), shell = True).wait()
subprocess.Popen('rm %s' % (lib_settings.get_mapped_reads_sam()), shell = True).wait()
lib_settings.write_to_log('mapping_reads done')
def rdir_path(self, *args):
return os.path.join(self.settings.get_rdir(), *args)
def get_rdir_fhandle(self, *args):
"""
returns a filehandle to the fname in the rdir
"""
out_path = self.rdir_path(*args)
out_dir = os.path.dirname(out_path)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
return ms_utils.aopen(out_path, 'w')
def perform_qc(self):
qc_engine = ms_qc.ms_qc(self, self.settings, self.threads)
qc_engine.write_mapping_summary(self.settings.get_overall_mapping_summary())
qc_engine.print_library_count_concordances()
qc_engine.plot_average_read_positions()
qc_engine.plot_fragment_length_distributions()
qc_engine.plot_count_distributions()
qc_engine.read_cutoff_choice_plot()
def make_counts_table(self, fractional=False):
"""
write out number of fragments mapping to each TL in each dataset
:param fractional: if True, replace raw counts with library fraction in reads per million
:return:
"""
if fractional:
summary_file = open(os.path.join(
self.rdir_path('tables'),
'rpm.txt'), 'w')
else:
summary_file = open(os.path.join(
self.rdir_path('tables'),
'raw_counts.txt'), 'w')
header = 'sequence name\t' + '\t'.join([lib.lib_settings.sample_name for lib in self.libs]) + '\n'
summary_file.write(header)
if fractional:
for sequence_name in self.libs[0].pool_sequence_mappings:
out_line = '%s\t%s\n' % (sequence_name,
'\t'.join(['%f' % ((10**6)*lib.pool_sequence_mappings[sequence_name].fragment_count/float(lib.total_mapped_fragments)) for lib in self.libs]))
summary_file.write(out_line)
else:
for sequence_name in self.libs[0].pool_sequence_mappings:
out_line = '%s\t%s\n' % (sequence_name,
'\t'.join(['%f' %
lib.pool_sequence_mappings[sequence_name].fragment_count
for lib in self.libs]))
summary_file.write(out_line)
summary_file.close()
def make_monosome_recruitment_table(self, read_cutoff=128):
"""
write out 80S recruitment metric for each TL in each replicate
:param read_cutoff: require this many read between mRNP and monosome to include this TL.
:return:
"""
output_file = open(os.path.join(
self.rdir_path('tables'),
'monosome_recruitment.txt'), 'w')
trimmed_sequences = ms_utils.convertFastaToDict(self.settings.get_trimmed_pool_fasta())
header = 'sequence name\tsequence\t' + '\t'.join(['%s/(%s+%s)' % (self.monosome_libs[i].lib_settings.sample_name,
self.monosome_libs[i].lib_settings.sample_name,
self.mrnp_libs[i].lib_settings.sample_name)
for i in range(len(self.monosome_libs))]) + '\n'
output_file.write(header)
for sequence_name in self.monosome_libs[0].pool_sequence_mappings:
out_line = '%s\t%s\t%s\n' % (sequence_name, trimmed_sequences[sequence_name],
'\t'.join(['%f' %
(self.monosome_libs[i].get_rpm(sequence_name)/
(self.monosome_libs[i].get_rpm(sequence_name)+
self.mrnp_libs[i].get_rpm(sequence_name)))
if (self.monosome_libs[i].get_counts(sequence_name) +
self.mrnp_libs[i].get_counts(sequence_name)) >= read_cutoff else ''
for i in range(len(self.monosome_libs)) ]))
output_file.write(out_line)
output_file.close()
def write_sequence_subset(self, recruitment_cutoff, read_cutoff=128, as_RNA=True):
"""
write out fasta of all sequences that pass a certain recruitment cutoff in all libraries
:return:
"""
output_file = open(os.path.join(
self.rdir_path('tables'),
'recruitment_above_%f.fasta' % recruitment_cutoff), 'w')
trimmed_sequences = ms_utils.convertFastaToDict(self.settings.get_trimmed_pool_fasta())
for sequence_name in self.monosome_libs[0].pool_sequence_mappings:
rec_scores = [(self.monosome_libs[i].get_rpm(sequence_name) / (self.monosome_libs[i].get_rpm(sequence_name) +
self.mrnp_libs[i].get_rpm(sequence_name)))
for i in range(len(self.monosome_libs)) if (self.monosome_libs[i].get_counts(sequence_name) +
self.mrnp_libs[i].get_counts(sequence_name)) >= read_cutoff]
if (len(rec_scores) == len(self.monosome_libs)):
average_score = np.average(rec_scores)
if average_score >=recruitment_cutoff:
output_file.write('>%s_rec_%f\n' % (sequence_name, average_score))
seq = trimmed_sequences[sequence_name]
if as_RNA:
seq = ms_utils.rna(seq)
output_file.write('%s\n' % (seq))
output_file.close()
def make_matched_recruitment_change_table(self, annotation_file, read_cutoff=128):
"""
write out number of fragments mapping to each TL in each dataset
:param read_cutoff: require this many read between mRNP and monosome to include this TL.
:return:
"""
set_name1, set_name2, matched_set = self.parse_matched_set_annotation(annotation_file)
output_file = open(os.path.join(
self.rdir_path('tables'),
'%s_%s_matched_monosome_recruitment_change.txt' % (set_name1, set_name2)), 'w')
header = '%s\t%s\t' % (set_name1, set_name2) + '\t'.join(['%s %s-%s recruitment score' % (self.monosome_libs[i].lib_settings.sample_name,
set_name1, set_name2)
for i in range(len(self.monosome_libs))]) + '\t'+\
'\t'.join(['%s %s/%s recruitment score' % (self.monosome_libs[i].lib_settings.sample_name,
set_name1, set_name2)
for i in range(len(self.monosome_libs))])+'\tttest p\n'
output_file.write(header)
for matched_pool_seqs in matched_set:
set1_scores = []
set2_scores = []
for i in range(len(self.monosome_libs)):
set_1_counts = self.monosome_libs[i].get_counts(matched_pool_seqs[0])\
+ self.mrnp_libs[i].get_counts(matched_pool_seqs[0])
set_2_counts = self.monosome_libs[i].get_counts(matched_pool_seqs[1]) \
+ self.mrnp_libs[i].get_counts(matched_pool_seqs[1])
# include only comparisons where the average number of reads is high enough
if set_1_counts >= read_cutoff and set_2_counts >= read_cutoff:
set1_score = self.monosome_libs[i].get_rpm(matched_pool_seqs[0]) / \
(self.monosome_libs[i].get_rpm(matched_pool_seqs[0]) +
self.mrnp_libs[i].get_rpm(matched_pool_seqs[0]))
set2_score = self.monosome_libs[i].get_rpm(matched_pool_seqs[1]) / \
(self.monosome_libs[i].get_rpm(matched_pool_seqs[1]) +
self.mrnp_libs[i].get_rpm(matched_pool_seqs[1]))
else:
set1_score = float('nan')
set2_score = float('nan')
set1_scores.append(set1_score)
set2_scores.append(set2_score)
recruitment_changes = np.array(set1_scores)-np.array(set2_scores)
recruitment_fold_changes = np.array(set1_scores)/np.array(set2_scores)
scores_1_filtered, scores_2_filtered = ms_utils.filter_x_y_pairs(set1_scores, set2_scores)
if len(scores_1_filtered)>0 and len(scores_2_filtered)>0:
t, p = stats.ttest_ind(scores_1_filtered, scores_2_filtered)
else:
p = float('nan')
out_line = '%s\t%s\t%s\t%s\t%f\n' % (matched_pool_seqs[0], matched_pool_seqs[1],
'\t'.join(['%f' % score_change for score_change in recruitment_changes]),
'\t'.join(['%f' % score_change for score_change in recruitment_fold_changes]),
p)
output_file.write(out_line)
output_file.close()
def parse_matched_set_annotation(self, filename):
matched_set = set()# a set of tuples matching a sequence name to one matched to it. sequences cana ppear multiple times, but the pairs ought to be unique
f = open(filename)
lines = f.readlines()
header = lines[0]
set_name1, set_name2 = header.strip().split('\t')
for line in lines[1:]:
seq_name1, seq_name2 = line.strip().split('\t')
matched_set.add((seq_name1, seq_name2))
f.close()
return set_name1, set_name2, matched_set
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("settings_file")
parser.add_argument("--make-tables",
help="Makes tables.",
action='store_true')
parser.add_argument("--perform-qc",
help="performs quality control analysis.",
action='store_true')
parser.add_argument("--make-plots",
help="Makes plots.",
action='store_true')
parser.add_argument("--comparisons",
help="Does comparisons to other experiments",
action='store_true')
parser.add_argument("--all-tasks",
help="Makes plots, tables, folding and comparisons",
action='store_true')
parser.add_argument("--threads",
help="Max number of processes to use",
type = int, default = 8)
args = parser.parse_args()
return args
def main():
"""
"""
args = parse_args()
settings = ms_settings.ms_settings(args.settings_file)
ms_experiment = mse(settings, args.threads)
print 'mse ready'
if args.perform_qc or args.all_tasks:
print 'QC'
settings.write_to_log('performing QC')
ms_experiment.perform_qc()
settings.write_to_log('done performing QC')
if args.make_tables or args.all_tasks:
print 'tables'
settings.write_to_log('making tables')
ms_experiment.make_tables()
settings.write_to_log('done making tables')
if args.make_plots or args.all_tasks:
print 'plots'
settings.write_to_log('making plots')
ms_experiment.make_plots()
settings.write_to_log('done making plots')
'''
if args.comparisons or args.all_tasks:
settings.write_to_log('doing comparisons')
ms_experiment.compare_all_other_experiments()
'''
main() | {
"repo_name": "borisz264/mono_seq",
"path": "mono_seq_main.py",
"copies": "1",
"size": "24383",
"license": "mit",
"hash": -6215894587800873000,
"line_mean": 54.2925170068,
"line_max": 269,
"alpha_frac": 0.5590780462,
"autogenerated": false,
"ratio": 3.8104391311142365,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48695171773142365,
"avg_score": null,
"num_lines": null
} |
__author__ = 'BoscoTsang'
import copy
import numpy
import scipy
from sklearn.cluster import KMeans
def SPLL(X1, X2, PARAM=None):
if PARAM is None:
k = 3
else:
k = PARAM
Ch = numpy.zeros(2)
ps = numpy.zeros(2)
s = numpy.zeros(2)
Ch[0], ps[0], s[0] = Log_LL(X1, X2, k)
Ch[1], ps[1], s[1] = Log_LL(X2, X1, k)
ind = numpy.argmax(s)
Change = Ch[ind]
st = s[ind]
pst = ps[ind]
return Change, pst, st
def Log_LL(X1, X2, k):
assert X1.shape[1] == X2.shape[1]
n = X1.shape[1]
kmean = KMeans(k, init=X1[:k, :], max_iter=100)
kmean.fit(X1)
labels = kmean.predict(X1)
means = kmean.cluster_centers_
SC = []
label_prior = numpy.zeros((1, k))
for i in xrange(k):
label_idx = labels == i
label_prior[0, i] = numpy.sum(label_idx)
if label_prior[0, i] < 1:
SC.append(numpy.zeros(n))
else:
if X1[label_idx, :].shape[0] > 1:
SC.append(numpy.diag(numpy.var(X1[label_idx, :], axis=0, ddof=1)).flatten())
else:
SC.append(numpy.diag(numpy.var(X1[label_idx, :], axis=0, ddof=0)).flatten())
SC = numpy.asarray(SC)
label_count = copy.deepcopy(label_prior)
label_prior /= X1.shape[0]
scov = numpy.sum(SC * numpy.tile(label_prior.T, (1, n ** 2)), axis=0)
scov = numpy.reshape(scov, (n, n))
z = numpy.array(numpy.diag(scov))
indexvarzero = z < numpy.spacing(1)
if numpy.sum(indexvarzero) == 0:
invscov = numpy.linalg.inv(scov)
else:
z[indexvarzero] = numpy.min(z[~indexvarzero])
invscov = numpy.diag(1. / z)
LogLikelihoodTerm = numpy.zeros(X2.shape[0])
for j in xrange(X2.shape[0]):
xx = X2[j, :]
DistanceToMeans = numpy.zeros(k)
for jj in xrange(k):
if label_count[0, jj] > 0:
DistanceToMeans[jj] = numpy.dot(numpy.dot((means[jj, :] - xx), invscov), (means[jj, :] - xx).T)
else:
DistanceToMeans[jj] = numpy.inf
LogLikelihoodTerm[j] = numpy.min(DistanceToMeans)
st = numpy.mean(LogLikelihoodTerm)
pst = min(scipy.stats.chi2.cdf(st, n), 1 - scipy.stats.chi2.cdf(st, n))
Change = pst < 0.05
return Change, pst, st
if "__main__" == __name__:
#a = numpy.array([[0.3, 1.4, 0.9], [0.2, 1.2, 0.7], [0.1, 1.0, 0.77], [0.4, 1.8, 0.9], [0.33, 1.3, 0.7]])
#b = numpy.array([[0.3, 1.2, 0.9], [0.2, 1.4, 0.7], [0.1, 1.3, 0.77], [0.4, 1.0, 0.9], [0.33, 1.8, 0.7]])
a = numpy.random.random((4, 4))
b = numpy.random.random((4, 4)) + 0.1
print a
print b
change, pst, st = SPLL(a, b, 3)
print change, pst, st
| {
"repo_name": "boscotsang/SPLL-Python",
"path": "SPLL.py",
"copies": "1",
"size": "2677",
"license": "mit",
"hash": 745278764219821700,
"line_mean": 30.4941176471,
"line_max": 111,
"alpha_frac": 0.5390362346,
"autogenerated": false,
"ratio": 2.5965082444228904,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8631615209367813,
"avg_score": 0.0007858539310152214,
"num_lines": 85
} |
__author__ = "Bo Shi"
__version__ = "0.2.1"
__date__ = "10/2008"
__copyright__ = """
Copyright (c) 2007, Bo Shi
Copyright (c) 2008, Julien Demoor
All rights reserved.
"""
__license__ = """
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name SNAPboard nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
#__history__ = ""
# vim: ai ts=4 sts=4 et sw=4
| {
"repo_name": "SarathkumarJ/snapboard",
"path": "snapboard/__init__.py",
"copies": "5",
"size": "1671",
"license": "bsd-3-clause",
"hash": 8683229756954421000,
"line_mean": 42.9736842105,
"line_max": 77,
"alpha_frac": 0.7707959306,
"autogenerated": false,
"ratio": 4.230379746835443,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.005091287755318106,
"num_lines": 38
} |
__author__ = 'Bouhm'
#Methods that access API and return dictionary/JSON files of data
#d
import requests
import json
import re
import pprint
from constants import URL_RIOT_API as API, API_VERSIONS as VER
class RiotAPIData(object):
def __init__(self, api_key, region='na'):
self.api_key = api_key
self.region = region
#Fetch API url and get JSON data
def _request(self, api_url, params={}):
args = {'api_key': self.api_key}
for key, value in params.items():
if key not in args:
args[key] = value
response = requests.get(
API['base'].format(
proxy = self.region,
region = self.region,
url = api_url
),
params = args
)
return response.json()
#Get all mercenaries and upgrades purchased in match
#Return python dictionary of mercenaries and upgrades
def _get_BMB_mercs(self):
args = {'api_key': self.api_key, 'itemListData': 'groups'}
api_url = API['item'].format(version=VER['lol_static_data'])
response = requests.get(
API['base_static_data'].format(
proxy = self.region,
region = self.region,
url = api_url
),
params=args
)
items = response.json()
merc = {}
merc_upgrade = []
for item in items['data'].values():
group = [value for key, value in item.items() if 'group' in key]
if len(group) != 0 and 'BWMerc' in group[0]:
if ('Upgrade' in group[0] or 'Offense' in group[0] or 'Defense' in group[0]):
merc_upgrade.append(item['id'])
else:
merc.update({item['id']:item['name']})
merc.update({'mercUpgrades':merc_upgrade})
return merc
#Get all relevant data from BMB matches
#Return dictionary of champion ids, champion item ids, mercenaries, and respective upgrades
def get_BMB_data(self, match_id=None, file=None):
if file == None:
match_data = self._request(
API['match'].format(
version = VER['match'],
match_id = match_id
),
{'includeTimeline':'true'}
)
else:
match_data = file
teams_data = self._get_teams_data(match_data)
# if teams_data['winner']['teamId'] == '100':
# winner = ['1', '2', '3', '4', '5']
# else:
# winner = ['6', '7', '8', '9', '10']
player_mercs = {}
timeline = match_data['timeline']['frames']
for events in timeline:
if 'events' in events.keys():
for event in events['events']:
if event['eventType'] == 'ITEM_PURCHASED':
item_id = event['itemId']
participant = str(event['participantId'])
if item_id in [3611, 3612, 3613, 3614]: #Mercenaries
player_mercs.update({participant:{'merc': item_id}})
player_mercs[participant].update({'offense': 0, 'defense':0, 'upgrade':0})
elif item_id in [3621, 3622, 3623]:
player_mercs[participant]['offense'] += 1
elif item_id in [3624, 3625, 3626]:
player_mercs[participant]['defense'] += 1
elif item_id in [3615, 3616, 3617]:
player_mercs[participant]['upgrade'] += 1
for player in player_mercs:
# if player in winner:
# team = 'winner'
# else:
# team = 'loser'
if float(player) < 6:
team = '100'
else :
team = '200'
merc_data = player_mercs[player].copy()
if player_mercs[player]['merc'] in teams_data[team].keys():
del merc_data['merc']
teams_data[team][player_mercs[player]['merc']].append(merc_data)
else:
del merc_data['merc']
teams_data[team].update({player_mercs[player]['merc']:[merc_data]})
return teams_data
#Get data from each team from given match data dictionary
#Return dictionary
def _get_teams_data(self, match_data):
winner = 0
loser = 0
#Exclude flasks, trinkets, wards
item_exc = [
'2140', '2138', '2139', '2137',
'3340', '3341', '3342', '3361', '3362', '3363', '3364',
'2043', '2044'
]
for team in match_data['teams']:
if team['winner'] == True:
winner = '100'
loser = '200'
else:
loser = '100'
winner = '200'
break
result = {'matchId':match_data['matchId'], winner:{'winner': True, 'champions':[]}, loser:{'winner': False, 'champions': []}}
for player in match_data['participants']:
if str(player['teamId']) == winner:
items = [value for key, value in player['stats'].items() if ('item' in key) and (str(value) not in item_exc)]
result[winner]['champions'].append({'championId': player['championId'], 'items': items})
else:
items = [value for key, value in player['stats'].items() if ('item' in key) and (str(value) not in item_exc)]
result[loser]['champions'].append({'championId': player['championId'], 'items': items})
return result
#Returns champion name string given champion id integer
def _get_champion_by_id(self, champion_id):
args = {'api_key': self.api_key, 'champData':'all'}
api_url = API['champion_by_id'].format(version=VER['lol_static_data'], champion_id = champion_id)
response = requests.get(
API['base_static_data'].format(
proxy = self.region,
region = self.region,
url = api_url
),
params = args
)
champion_data = response.json()
return champion_data['name']
#Get latest static version to access Riot's static data database
def _get_static_data_version(self):
args = {'api_key': self.api_key}
api = API['versions'].format(version=VER['lol_static_data'])
response = requests.get(API['base_static_data'].format(
proxy = self.region,
region = self.region,
url = api),
params = args
)
versions = response.json()
return versions[0]
def get_all_items(self):
args = {'api_key': self.api_key}
api_url = API['item'].format(version=VER['lol_static_data'])
response = requests.get(
API['base_static_data'].format(
proxy = self.region,
region = self.region,
url = api_url
),
params=args
)
items = response.json()
version = self._get_static_data_version()
item_list = []
for item in items['data'].values():
img_url = API['item_img'].format(version=version, item=item['id']) + ".png"
item_data = {'itemId': item['id'], 'name': item['name'], 'img': img_url}
item_list.append(item_data)
return json.dumps(item_list)
#Get all champion names, IDs, and image URIs
#Return JSON file of data
def get_all_champs(self):
version = self._get_static_data_version()
args = {'api_key': self.api_key, 'champData': 'image'}
url = API['champion'].format(version=VER['lol_static_data'])
response = requests.get(
API['base_static_data'].format(
proxy = self.region,
region = self.region,
url = url
),
params = args
)
champions = response.json()
champions_data = []
for champion in champions['data'].values():
champ_data = {
'name': champion['name'],
'championId': champion['id'],
'img': API['champion_img'].format(version=version, champion=champion['image']['full'])
}
champions_data.append(champ_data)
return json.dumps(champions_data)
# For offline testing
def _test_sample_data(self):
with open("sample.json") as file:
return json.load(file)
| {
"repo_name": "Bouhm/BlackMarketDefense",
"path": "riot_API_data.py",
"copies": "1",
"size": "8596",
"license": "mit",
"hash": -1868607141843864300,
"line_mean": 37.5470852018,
"line_max": 133,
"alpha_frac": 0.5090739879,
"autogenerated": false,
"ratio": 3.825545171339564,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4834619159239564,
"avg_score": null,
"num_lines": null
} |
__author__ = 'Bouhm'
#Program that uses methods from RiotAPIStats for data aggregation
#For data analysis and data format for game
from riot_API_data import RiotAPIData
import keys
import pprint
import json
import random
import math
import time
import ast
def main():
api = RiotAPIData(keys.API_KEY)
pprint.pprint(get_game_data_format(api, 'NA', 100, 20))
#Convert all ids to names in python dictionary, key value pairs are appropriately replaced
def id_to_name(dict):
with open("database/items.json") as file:
item_data = json.load(file)
with open("database/champions.json") as file:
champ_data = json.load(file)
for x in range (1, 3):
team = dict[str(x*100)]
for key, value in team.items():
if key == 'champions':
for champion in team[key]:
for champ in champ_data:
if 'championId' in champion.keys() and champion['championId'] == champ['championId']:
champion['name'] = champ['name']
for champ in champ_data:
champion.pop('championId', None)
for item in champion['items']:
for item_name in item_data:
if item == item_name['itemId']:
champion['items'].append(item_name['name'])
champion['items'] = [x for x in champion['items'] if not isinstance(x, int)]
else:
for item in item_data:
if item['itemId'] == key:
team.update({item['name']:team[key]})
del team[key]
return dict
#From match data get game data
def get_game_data_format(api, region, num, totalWaves, local):
all_waves = {}
matches_data = []
if local == 0:
with open("dataset/" + region + ".json") as file:
matches_list = json.load(file)
matches = random.sample(range(1,10000), num)
for x in range (1, 10000):
#for match in matches:
try:
matches_data.append(id_to_name(api.get_BMB_data(matches_list[x])))
time.sleep(1.3)
except:
pass
else:
with open("database/matches_data_" + region + ".json") as file:
matches_data = json.load(file)
for data in matches_data:
matches_data.append(id_to_name(data))
for match in matches_data:
team = match['100']
wave = match['200']
stats = 0
upgrades = 0
count = 0
waves = {}
champions = []
towers = []
merc_wave = wave.copy()
mercs = team.copy()
del merc_wave['winner']
del merc_wave['champions']
del mercs['winner']
del mercs['champions']
merc_wave.update({'mercs': mercs})
for champion in wave['champions']:
if 'name' in champion.keys():
champions.append(champion['name'])
merc_wave.update({'champions': champions})
for champion in team['champions']:
if 'name' in champion.keys():
towers.append(champion['name'])
#WAVE SORTING ALGORITHM (BASED ON UPGRADES & NUMBER OF MERCS AND RESPECTIVE DISTRIBUTION (SUPER BASIC))
#Currently only optimized for 20
if 'Ironback' in wave.keys():
count += len(wave['Ironback'])
for upgrade in wave['Ironback']:
stats += upgrade['offense'] + upgrade['defense']
upgrades += upgrade['upgrade'] * 2
if 'Razorfin' in wave.keys():
count += len(wave['Razorfin'])
for upgrade in wave['Razorfin']:
stats += upgrade['offense'] + upgrade['defense']
upgrades += upgrade['upgrade'] * 2
if 'Ocklepod' in wave.keys():
count += len(wave['Ocklepod'])
for upgrade in wave['Ocklepod']:
stats += upgrade['offense'] + upgrade['defense']
upgrades += upgrade['upgrade'] * 2
if 'Plundercrab' in wave.keys():
count += len(wave['Plundercrab'])
for upgrade in wave['Plundercrab']:
stats += upgrade['offense'] + upgrade['defense']
upgrades += upgrade['upgrade'] * 2
if count > 3:
x = 0
for waveNum in range (1, totalWaves + 1):
if stats + upgrades <= x:
k = "wave" + str(waveNum)
break
x += 3
waves.update({'wave': merc_wave})
waves.update({'towers': towers})
waves.update({'matchId': match['matchId']})
if k in all_waves.keys():
all_waves[k].append(waves)
else:
all_waves.update({k: [waves]})
return json.dumps(all_waves)
#For data analysis
def winrate_data(region):
with open("database/items.json") as file:
item_data = json.load(file)
with open("database/champions.json") as file:
champ_data = json.load(file)
with open("database/matches_data_" + region + ".json", 'r') as file:
BMB_data = json.load(file)
champion_wr = {}
mercenary_wr = {}
item_wr = {}
#mercs = {"3611":"Razorfin", "3612":"Ironback", "3613":"Plundercrab", "3614":"Ocklepod"}
for match in BMB_data:
for x in range (1, 3):
if match[str(x * 100)]['winner'] == "True":
win = 1
else:
win = 0
for champion in match[str(x * 100)]['champions']:
for champ in champ_data:
if champion['championId'] == champ['championId']:
if champ['name'] not in champion_wr.keys():
champion_wr.update({champ['name']:{'wins':1, 'games':1, 'winrate':win}})
else:
champion_wr[champ['name']]['wins'] += win
champion_wr[champ['name']]['games'] += 1
champion_wr[champ['name']]['winrate'] = champion_wr[champ['name']]['wins']/champion_wr[champ['name']]['games']
for item in champion['items']:
for item_name in item_data:
if item == item_name['itemId']:
if item_name['name'] not in item_wr.keys():
item_wr.update({item_name['name']:{'wins':1, 'games':1, 'winrate':win}})
else:
item_wr[item_name['name']]['wins'] += win
item_wr[item_name['name']]['games'] += 1
item_wr[item_name['name']]['winrate'] = item_wr[item_name['name']]['wins']/item_wr[item_name['name']]['games']
if '3611' in match[str(x * 100)].keys():
for stats in match[str(x * 100)]['3611']:
k = "off: " + str(stats['offense']) + ", def: " + str(stats['defense']) + ", upg: " + str(stats['upgrade'])
if 'Razorfin' not in mercenary_wr.keys():
mercenary_wr.update({'Razorfin':{'wins':win, 'games':1, 'winrate':win, k:{'wins':win, 'games':1, 'winrate':win}}})
else:
mercenary_wr['Razorfin']['wins'] += win
mercenary_wr['Razorfin']['games'] += 1
mercenary_wr['Razorfin']['winrate'] = mercenary_wr['Razorfin']['wins']/mercenary_wr['Razorfin']['games']
if k not in mercenary_wr['Razorfin'].keys():
mercenary_wr['Razorfin'].update({k:{'wins':win, 'games':1, 'winrate':win}})
else:
mercenary_wr['Razorfin'][k]['wins'] += win
mercenary_wr['Razorfin'][k]['games'] += 1
mercenary_wr['Razorfin'][k]['winrate'] = mercenary_wr['Razorfin'][k]['wins']/ mercenary_wr['Razorfin'][k]['games']
#mercenary_wr['Razorfin'][k].sort(key=lambda e: e['winrate'])
if '3612' in match[str(x * 100)].keys():
for stats in match[str(x * 100)]['3612']:
k = "off: " + str(stats['offense']) + ", def: " + str(stats['defense']) + ", upg: " + str(stats['upgrade'])
if 'Ironback' not in mercenary_wr.keys():
mercenary_wr.update({'Ironback':{'wins':win, 'games':1, 'winrate':win, k:{'wins':win, 'games':1, 'winrate':win}}})
else:
mercenary_wr['Ironback']['wins'] += win
mercenary_wr['Ironback']['games'] += 1
mercenary_wr['Ironback']['winrate'] = mercenary_wr['Ironback']['wins']/mercenary_wr['Ironback']['games']
if k not in mercenary_wr['Ironback'].keys():
mercenary_wr['Ironback'].update({k:{'wins':win, 'games':1, 'winrate':win}})
else:
mercenary_wr['Ironback'][k]['wins'] += win
mercenary_wr['Ironback'][k]['games'] += 1
mercenary_wr['Ironback'][k]['winrate'] = mercenary_wr['Ironback'][k]['wins']/ mercenary_wr['Ironback'][k]['games']
#mercenary_wr['Ironback'][k].sort(key=lambda e: e['winrate'])
if '3613' in match[str(x * 100)].keys():
for stats in match[str(x * 100)]['3613']:
k = "off: " + str(stats['offense']) + ", def: " + str(stats['defense']) + ", upg: " + str(stats['upgrade'])
if 'Plundercrab' not in mercenary_wr.keys():
mercenary_wr.update({'Plundercrab':{'wins':win, 'games':1, 'winrate':win, k:{'wins':win, 'games':1, 'winrate':win}}})
else:
mercenary_wr['Plundercrab']['wins'] += win
mercenary_wr['Plundercrab']['games'] += 1
mercenary_wr['Plundercrab']['winrate'] = mercenary_wr['Plundercrab']['wins']/mercenary_wr['Plundercrab']['games']
if k not in mercenary_wr['Plundercrab'].keys():
mercenary_wr['Plundercrab'].update({k:{'wins':win, 'games':1, 'winrate':win}})
else:
mercenary_wr['Plundercrab'][k]['wins'] += win
mercenary_wr['Plundercrab'][k]['games'] += 1
mercenary_wr['Plundercrab'][k]['winrate'] = mercenary_wr['Plundercrab'][k]['wins']/ mercenary_wr['Plundercrab'][k]['games']
#mercenary_wr['Plundercrab'][k].sort(key=lambda e: e['winrate'])
if '3614' in match[str(x * 100)].keys():
for stats in match[str(x * 100)]['3614']:
k = "off: " + str(stats['offense']) + ", def: " + str(stats['defense']) + ", upg: " + str(stats['upgrade'])
if 'Ocklepod' not in mercenary_wr.keys():
mercenary_wr.update({'Ocklepod':{'wins':win, 'games':1, 'winrate':win, k:{'wins':win, 'games':1, 'winrate':win}}})
else:
mercenary_wr['Ocklepod']['wins'] += win
mercenary_wr['Ocklepod']['games'] += 1
mercenary_wr['Ocklepod']['winrate'] = mercenary_wr['Ocklepod']['wins']/mercenary_wr['Ocklepod']['games']
if k not in mercenary_wr['Ocklepod'].keys():
mercenary_wr['Ocklepod'].update({k:{'wins':win, 'games':1, 'winrate':win}})
else:
mercenary_wr['Ocklepod'][k]['wins'] += win
mercenary_wr['Ocklepod'][k]['games'] += 1
mercenary_wr['Ocklepod'][k]['winrate'] = mercenary_wr['Ocklepod'][k]['wins']/ mercenary_wr['Ocklepod'][k]['games']
#mercenary_wr['Ocklepod'][k].sort(key=lambda e: e['winrate'])
return ({'champions':champion_wr, 'mercenaries':mercenary_wr, 'items':item_wr})
def match_ids(region):
return
if __name__ == "__main__":
main()
| {
"repo_name": "Bouhm/BlackMarketDefense",
"path": "data_aggr.py",
"copies": "1",
"size": "12231",
"license": "mit",
"hash": 3403711875374028300,
"line_mean": 49.7510373444,
"line_max": 151,
"alpha_frac": 0.4878587196,
"autogenerated": false,
"ratio": 3.4975693451529883,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4485428064752988,
"avg_score": null,
"num_lines": null
} |
__author__ = 'Bouhm'
#Program that uses methods from RiotAPIStats mainly for building database
#Database used for game
from riot_API_data import RiotAPIData
import data_aggr
import keys
import os.path
import urllib.request
import sys
import requests
import json
import random
from pprint import pprint
import time
import math
def main():
headers = {
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)",
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"accept-charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
"accept-encoding": "gzip,deflate,sdch",
"accept-language": "en-US,en;q=0.8",
}
print("Choose region: ")
region = input(': ')
api = RiotAPIData(keys.API_KEY, region)
print("")
print("Options: ")
print("(1) Update item list")
print("(2) Update champion list")
print("(3) Update data from matches")
print("(4) Get winrates")
print("(5) Combine winrate data")
print("(6) Update game data")
print("(7) Overflow data")
print("(8) Condense data")
option = input(':')
if option == '1':
item_data(api, headers, False)
elif option == '2':
champion_data(api, headers, False)
elif option == '3':
data_from_matches(api, region, 2)
elif option == '4':
get_winrates(region)
elif option == '5':
combine_winrate_data('na', 'euw')
elif option == '6':
game_data(api, region, 10, 20, 1)
elif option == '7':
overflow_data(20)
elif option == '8':
condense_data(20)
#Get static item data and save item name, ID, and image URI to local db
def item_data(api, headers, img):
item_data = api.get_all_items()
if not os.path.isfile("database/items.json"):
file = open("database/items.json", 'w+')
#for item in item_data:
file.write("%s \n" % item_data)
else:
with open("database/items.json", 'a') as file:
#for item in item_data:
file.write("%s\n" % item_data)
if(img):
for item in item_data:
r = requests.get(item['img'], headers=headers)
if r.status_code != 200:
print("Request denied")
sys.exit()
urllib.request.urlretrieve(item['img'], "database/item_img/" + str(item['itemId']) + ".png")
urllib.request.urlcleanup()
#Get static champion data and store name, ID, and image URI to local db
def champion_data(api, headers, img):
champion_data = api.get_all_champs()
if not os.path.isfile("database/champions.json"):
file = open("database/champions.json", 'w+')
#for champ in champion_data:
file.write("%s \n" % champion_data)
else:
with open("database/champions.json", 'a') as file:
#for champ in champion_data:
file.write("%s\n" % champion_data)
if(img):
for champ in champion_data:
r = requests.get(champ['img'], headers=headers)
if r.status_code != 200:
print("Request denied")
sys.exit()
urllib.request.urlretrieve(champ['img'], "database/champ_img/" + champ['name'] + ".png")
urllib.request.urlcleanup()
#From match data get game data and save
def game_data(api, region, num, totalWaves, local):
game_data = json.dumps(data_aggr.get_game_data_format(api, region, num, totalWaves, local))
if not os.path.isfile("database/game_data_" + region + ".json"):
file = open("database/game_data_" + region + ".json", 'w+')
#for champ in champion_data:
file.write("%s \n" % game_data)
else:
with open("database/game_data_" + region + ".json", 'a') as file:
#for champ in champion_data:
file.write("%s\n" % game_data)
return
#For making adjustments to wave sorting in game data
def condense_data(max):
with open("database/game_data.json") as file:
game_data = json.load(file)
for x in range (1, 21):
size = len(game_data['wave' + str(x)])
while len(game_data['wave' + str(x)]) > max:
index = random.randint(0, size - 1)
game_data['wave' + str(x)].remove(game_data['wave' + str(x)][index])
size -= 1
game_data = json.dumps(game_data)
if not os.path.isfile("database/game_data_min.json"):
file = open("database/game_data_min.json", 'w+')
#for champ in champion_data:
file.write("%s \n" % game_data)
else:
with open("database/game_data_min.json", 'a') as file:
#for champ in champion_data:
file.write("%s\n" % game_data)
return
#This method because I don't want to run a script for 3-5 hours again
def overflow_data(numMatches):
with open("database/game_data2.json") as file:
game_data = json.load(file)
di_size = len(game_data.keys())
#matches = game_data.copy()
for x in range (1, 20):
list_size = len(game_data['wave' + str(21 - x)])
for y in range (1, math.floor(list_size/2) + 1):
data = game_data['wave' + str(21 - x)].pop()
if 'wave' + str(20 - x) not in game_data.keys():
game_data.update({'wave' + str(20 - x): [data]})
else:
game_data['wave' + str(20 - x)].insert(0, data)
game_data = json.dumps(game_data)
if not os.path.isfile("database/game_data_OF.json"):
file = open("database/game_data_OF.json", 'w+')
#for champ in champion_data:
file.write("%s \n" % game_data)
else:
with open("database/game_data_OF.json", 'a') as file:
#for champ in champion_data:
file.write("%s\n" % game_data)
return
#Get data from matches, more useful for data analysis
def data_from_matches(api, region, num):
with open("dataset/" + region + ".json") as file:
matches_list = json.load(file)
matches = random.sample(range(1,10000), num)
matches_data = []
matches_data_s = []
for x in range (1, 10000):
try:
match_data = json.dumps(api.get_BMB_data(matches_list[x]))
matches_data.append(match_data)
time.sleep(1.3)
except:
pass
if not os.path.isfile("database/matches_data_" + region + ".json"):
file = open("database/matches_data_" + region + " .json", 'w+')
file.write("%s \n" % matches_data)
else:
with open("database/matches_data_" + region + ".json", 'a') as file:
file.write("%s\n" % matches_data)
return
#Convert all ids in python dictionary into names, key and value pairs are appropriately replaced
def id_to_name(dict):
with open("database/items.json") as file:
item_data = json.load(file)
with open("database/champions.json") as file:
champ_data = json.load(file)
for x in range (1, 3):
team = dict[str(x*100)]
for key, value in team.items():
if key == 'champions':
for champion in team[key]:
for champ in champ_data:
if 'championId' in champion.keys() and champion['championId'] == champ['championId']:
champion['name'] = champ['name']
for champ in champ_data:
champion.pop('championId', None)
for item in champion['items']:
for item_name in item_data:
if item == item_name['itemId']:
champion['items'].append(item_name['name'])
champion['items'] = [x for x in champion['items'] if not isinstance(x, int)]
else:
for item in item_data:
if item['itemId'] == key:
team.update({item['name']:team[key]})
del team[key]
return dict
def get_winrates(region):
winrate_data = data_aggr.winrate_data(region)
winrate_data = json.dumps(winrate_data)
if not os.path.isfile("database/winrate_data_" + region + ".json"):
file = open("database/winrate_data_" + region + ".json", 'w+')
#pprint(winrate_data, stream=file)
file.write("%s \n" % winrate_data)
else:
with open("database/winrate_data_" + region + ".json", 'a') as file:
#pprint(winrate_data, stream=file)
file.write("%s \n" % winrate_data)
return
def format_data():
with open("database/matches_data_id.json", 'r') as file:
BMB_data = json.load(file)
if not os.path.isfile("database/matches_data_list.json"):
file = open("database/matches_data_list.json", 'w+')
for datum in BMB_data:
if not os.path.isfile("database/matches_data_list.json"):
file = open("database/matches_data_list.json", 'w+')
file.write("%s \n" % datum + ",")
else:
with open("database/matches_data_list.json", 'a') as file:
for datum in BMB_data:
file.write("%s\n" % datum + ",")
return
def combine_winrate_data(region1, region2):
with open("database/winrate_data_" + region1 + ".json", 'r') as file:
wr_data1 = json.load(file)
with open("database/winrate_data_" + region2 + ".json", 'r') as file:
wr_data2 = json.load(file)
wr_data = wr_data1.copy()
for champion in wr_data1['champions']:
if champion in wr_data2['champions'].keys():
wr_data['champions'][champion]['games'] += wr_data2['champions'][champion]['games']
wr_data['champions'][champion]['wins'] += wr_data2['champions'][champion]['wins']
wr_data['champions'][champion]['winrate'] = wr_data['champions'][champion]['wins']/wr_data['champions'][champion]['games']
else:
wr_data['champions'][champion] = wr_data2['champions'][champion]
for mercenary in wr_data1['mercenaries']:
if mercenary in wr_data2['mercenaries'].keys():
wr_data['mercenaries'][mercenary]['wins'] += wr_data2['mercenaries'][mercenary]['wins']
wr_data['mercenaries'][mercenary]['games'] += wr_data2['mercenaries'][mercenary]['games']
wr_data['mercenaries'][mercenary]['winrate'] = wr_data['mercenaries'][mercenary]['wins']/ wr_data['mercenaries'][mercenary]['games']
for stats in wr_data1['mercenaries'][mercenary]:
if stats in wr_data2['mercenaries'].keys():
wr_data['mercenaries'][mercenary][stats]['games'] += wr_data2['mercenaries'][mercenary][stats]['games']
wr_data['mercenaries'][mercenary][stats]['wins'] += wr_data2['mercenaries'][mercenary][stats]['wins']
wr_data['mercenaries'][mercenary][stats]['winrate'] = wr_data['mercenaries'][mercenary][stats]['wins']/wr_data['mercenaries'][mercenary][stats]['games']
else:
wr_data['mercenaries'][mercenary][stats] = wr_data2['mercenaries'][mercenary][stats]
if not os.path.isfile("database/winrate_data_" + region1 + region2 + ".json"):
file = open("database/winrate_data_" + region1 + region2 + ".json", 'w+')
pprint(wr_data, stream=file)
#file.write("%s \n" % winrate_data)
else:
with open("database/winrate_data_" + region1 + region2 + ".json", 'a') as file:
pprint(wr_data, stream=file)
#file.write("%s \n" % winrate_data)
if __name__ == "__main__":
main()
| {
"repo_name": "Bouhm/BlackMarketDefense",
"path": "db_write.py",
"copies": "1",
"size": "11494",
"license": "mit",
"hash": 1395092419006626600,
"line_mean": 40.7963636364,
"line_max": 172,
"alpha_frac": 0.5695145293,
"autogenerated": false,
"ratio": 3.309530665131011,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.43790451944310105,
"avg_score": null,
"num_lines": null
} |
__author__ = 'bouska'
from datetime import datetime, timedelta
from StringIO import StringIO
class Event(object):
def __init__(self):
self.summary = ""
self.organizer = ""
self.location = ""
self.description = ""
self.start = None
self.duration = None
class Calendar(object):
def __init__(self):
self.name = ""
self.description = ""
self.version = "2.0"
self.provider = "https://bitbucket.org/odebeir/geholimport"
self.start_date = datetime.today()
self.events = []
def add_event(self, event):
self.events.append(event)
def as_string(self):
def write_line(out, line):
out.write(line+'\n')
out = StringIO()
def dirty_fix(duration):
def total_seconds(td):
return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
seconds = total_seconds(duration)
hours = seconds / 60 / 60
minutes = seconds / 60 % 60
return "%02i:%02i" % (hours, minutes)
for event in self.events:
write_line(out, "REM %s AT %s DURATION %s MSG %s (%s)" %
(str(event.start.strftime("%b %d %Y")),
str(event.start.strftime("%H:%M")),
str(dirty_fix(event.duration)),
str(event.summary.encode("Utf-8")),
str(event.location)))
ical_string = out.getvalue()
out.close()
return ical_string
def convert_geholcalendar_to_remind(gehol_calendar, first_monday):
date_init = datetime.strptime(first_monday,'%d/%m/%Y')
cal = Calendar()
cal.description = gehol_calendar.description
cal.name = gehol_calendar.name
cal.start_date = date_init
for event in gehol_calendar.events:
remind_event = Event()
for (i, event_week) in enumerate(event.weeks):
delta = timedelta(days=(event_week-1)*7 + event.day)
start = date_init+delta + timedelta(hours = event.start_time.hour,
minutes = event.start_time.minute)
duration = timedelta(hours = event.stop_time.hour,
minutes = event.stop_time.minute) - timedelta(hours = event.start_time.hour, minutes = event.start_time.minute)
remind_event = Event()
remind_event.summary = event.summary
remind_event.location = event.location
#remind_event.description = event.description
#remind_event.organizer = event.organizer
remind_event.start = start
remind_event.duration = duration
cal.add_event(remind_event)
return cal
| {
"repo_name": "Psycojoker/geholparser",
"path": "src/gehol/converters/remindwriter.py",
"copies": "1",
"size": "2796",
"license": "mit",
"hash": -686036909865581600,
"line_mean": 30.4157303371,
"line_max": 146,
"alpha_frac": 0.5500715308,
"autogenerated": false,
"ratio": 3.971590909090909,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5021662439890909,
"avg_score": null,
"num_lines": null
} |
__author__ = 'bperozzi'
import graph_tool.all as gt
import seaborn as sns
def find_color(value, maxv, minv, palette):
# XXX need to get min in there
percentage = (value - minv) / (maxv - minv)
idx = int(percentage * len(palette))
idx = min(len(palette) - 1, idx)
#print value, idx
#print palette[idx]
return list(palette[idx]) + [1.0]
def draw_graph_heatmap(graph, value_map, output, directed=False, palette=sns.cubehelix_palette(10, start=.5, rot=-.75), position=None):
# for normalize
values = value_map.values()
maxv = max(values)
minv = min(values)
if len(values) != len(graph):
# some graph nodes missing from map.
# make them 0
minv = min(minv, 0)
gt_graph = gt.Graph(directed=directed)
node_map = {node: gt_graph.add_vertex() for node in graph}
if not directed:
seen_edges = set()
for node, edges in graph.iteritems():
i = node_map[node]
for e in edges:
j = node_map[e]
if directed:
gt_graph.add_edge(i, j)
else:
if (j, i) not in seen_edges:
gt_graph.add_edge(i, j)
seen_edges.add((i, j))
node_intensity = gt_graph.new_vertex_property("vector<float>")
node_label = gt_graph.new_vertex_property("string")
for id, value in value_map.iteritems():
node = node_map[id]
node_intensity[node] = find_color(value, maxv, minv, palette)
node_label[node] = id
for id in graph:
if id not in value_map:
node = node_map[id]
node_intensity[node] = find_color(0, maxv, minv, palette)
node_label[node] = id
if position is None:
position = gt.sfdp_layout(gt_graph)
gt.graph_draw(gt_graph, pos=position,
vertex_text=node_label,
vertex_fill_color=node_intensity,
output=output)
return position
def draw_graph(graph, value_map=None, output=None, show_ids=False, directed=False, position=None):
gt_graph = gt.Graph(directed=directed)
node_map = {node: gt_graph.add_vertex() for node in graph}
if not directed:
seen_edges = set()
for node, edges in graph.iteritems():
i = node_map[node]
for e in edges:
j = node_map[e]
if directed:
gt_graph.add_edge(i, j)
else:
if (j, i) not in seen_edges:
gt_graph.add_edge(i, j)
seen_edges.add((i, j))
if position is None:
position = gt.sfdp_layout(gt_graph)
node_label = gt_graph.new_vertex_property("string")
if value_map is not None:
for id, value in value_map.iteritems():
node = node_map[id]
node_label[node] = id
for id in graph:
if id not in value_map:
node = node_map[id]
node_label[node] = id
elif show_ids:
for id in graph:
node = node_map[id]
node_label[node] = id
if show_ids:
gt.graph_draw(gt_graph, pos=position,
vertex_text=node_label,
output=output)
else:
gt.graph_draw(gt_graph, pos=position, output=output)
return position | {
"repo_name": "phanein/magic-graph",
"path": "src/magicgraph/visualization.py",
"copies": "1",
"size": "3005",
"license": "bsd-3-clause",
"hash": 4217968771521474000,
"line_mean": 23.048,
"line_max": 135,
"alpha_frac": 0.6093178037,
"autogenerated": false,
"ratio": 3.159831756046267,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9180030076497447,
"avg_score": 0.017823896649763773,
"num_lines": 125
} |
__author__ = 'bptripp'
# CNN with support and object depth maps as input.
import numpy as np
from os.path import join
import scipy
import cPickle
from keras.models import Sequential
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.optimizers import Adam, RMSprop
from data import load_all_params
im_width = 80
model = Sequential()
model.add(Convolution2D(32, 9, 9, input_shape=(2,im_width,im_width), init='glorot_normal', border_mode='same'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Convolution2D(32, 3, 3, init='glorot_normal', border_mode='same'))
model.add(Activation('relu'))
#model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Convolution2D(32, 3, 3, init='glorot_normal', border_mode='same'))
model.add(Activation('relu'))
model.add(Dropout(.25))
model.add(Flatten())
model.add(Dense(512))
model.add(Activation('relu'))
#model.add(Dropout(.25))
model.add(Dense(512))
model.add(Activation('relu'))
#model.add(Dropout(.25))
model.add(Dense(64))
model.add(Activation('relu'))
#model.add(Dropout(.25))
model.add(Dense(1))
model.add(Activation('sigmoid'))
#from keras.models import model_from_json
#model = model_from_json(open('v-model-architecture.json').read())
#model.load_weights('v-model-weights.h5')
rmsp = RMSprop(lr=0.001, rho=0.9, epsilon=1e-06)
adam = Adam(lr=0.00001, beta_1=0.9, beta_2=0.999, epsilon=1e-08)
model.compile(loss='binary_crossentropy', optimizer=adam)
objects, gripper_pos, gripper_orient, labels = load_all_params('../../grasp-conv/data/output_data.csv')
seq_nums = np.arange(len(objects)) % 1000 #exactly 1000 per object in above file (dated March 18)
labels = np.array(labels)[:,np.newaxis]
n = len(objects)
validation_indices = np.random.randint(0, n, 500) #TODO: generalize across objects
s = set(validation_indices)
train_indices = [x for x in range(n) if x not in s]
#train_indices = train_indices[:1000]
def get_input(object, seq_num):
image_file = object[:-4] + '-' + str(seq_num) + '.png'
X = []
image_dir = '../../grasp-conv/data/obj_depths/'
image = scipy.misc.imread(join(image_dir, image_file))
rescaled_distance = image / 255.0
X.append(1.0 - rescaled_distance)
image_dir = '../../grasp-conv/data/support_depths/'
image = scipy.misc.imread(join(image_dir, image_file))
rescaled_distance = image / 255.0
X.append(1.0 - rescaled_distance)
return np.array(X)
Y_valid = labels[validation_indices,:]
X_valid = []
for ind in validation_indices:
X_valid.append(get_input(objects[ind], seq_nums[ind]))
X_valid = np.array(X_valid)
def generate_XY():
while 1:
ind = train_indices[np.random.randint(len(train_indices))]
Y = np.zeros((1,1))
Y[0,0] = labels[ind,0]
X = get_input(objects[ind], seq_nums[ind])
X = X[np.newaxis,:,:,:]
#print('ind ' + str(ind) + ' Y ' + str(Y))
yield (X, Y)
h = model.fit_generator(generate_XY(),
samples_per_epoch=500, nb_epoch=1500,
validation_data=(X_valid, Y_valid))
f = file('v-history.pkl', 'wb')
cPickle.dump(h.history, f)
f.close()
json_string = model.to_json()
open('v-model-architecture.json', 'w').write(json_string)
model.save_weights('v-model-weights.h5', overwrite=True)
| {
"repo_name": "bptripp/grasp-convnet",
"path": "py/vrep_model.py",
"copies": "1",
"size": "3319",
"license": "mit",
"hash": -8229903321220664000,
"line_mean": 30.6095238095,
"line_max": 111,
"alpha_frac": 0.6869539018,
"autogenerated": false,
"ratio": 2.841609589041096,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8947663598792206,
"avg_score": 0.01617997840977817,
"num_lines": 105
} |
__author__ = 'bptripp'
# Convolutional network for grasp success prediction
import numpy as np
from keras.models import Sequential
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.optimizers import Adam
import cPickle
from tuning import disp_tuning
from depthmap import get_distance
def get_bowls():
shapes = [
'24_bowl-16-Feb-2016-10-12-27',
'24_bowl-17-Feb-2016-22-00-34',
'24_bowl-24-Feb-2016-17-38-53',
'24_bowl-26-Feb-2016-08-35-29',
'24_bowl-27-Feb-2016-23-52-43',
'24_bowl-29-Feb-2016-15-01-53']
distances = []
box_distances = []
labels = []
for shape in shapes:
f = file('../data/depths/' + shape + '.pkl', 'rb')
d, bd, l = cPickle.load(f)
f.close()
dist = get_distance(d, .2, 1.0)
box_dist = get_distance(bd, .2, 1.0)
distances.extend(dist.tolist())
box_distances.extend(box_dist.tolist())
labels.extend(l.tolist())
return np.array(distances), np.array(box_distances), np.array(labels)
def make_datasets(distances, box_distances, labels):
# try more like disparity with zero background
distances = 1 - distances
box_distances = 1 - box_distances
indices = np.arange(len(labels))
validation_flags = indices % 10 == 9
training_flags = ~validation_flags
n_train = len(labels[training_flags])
n_validation = len(labels[validation_flags])
X_train = np.zeros((n_train,2,distances.shape[1],distances.shape[2]))
X_valid = np.zeros((n_validation,2,distances.shape[1],distances.shape[2]))
X_train[:,0,:,:] = distances[training_flags,:,:]
X_train[:,1,:,:] = box_distances[training_flags,:,:]
X_valid[:,0,:,:] = distances[validation_flags,:,:]
X_valid[:,1,:,:] = box_distances[validation_flags,:,:]
Y_train = labels[training_flags]
Y_valid = labels[validation_flags]
return X_train, Y_train, X_valid, Y_valid
distances, box_distances, labels = get_bowls()
X_train, Y_train, X_valid, Y_valid = make_datasets(distances, box_distances, labels)
print(X_train.shape)
print(Y_train.shape)
print(X_valid.shape)
print(Y_valid.shape)
imsize = (X_train.shape[2],X_train.shape[3])
model = Sequential()
model.add(Convolution2D(32, 10, 10, input_shape=(2,imsize[0],imsize[1]), init='glorot_normal', border_mode='same'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
# model.add(Dropout(.5))
model.add(Convolution2D(32, 5, 5, init='glorot_normal', border_mode='same'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
# model.add(Dropout(.5))
model.add(Convolution2D(32, 5, 5, init='glorot_normal', border_mode='same'))
model.add(Activation('relu'))
# model.add(Dropout(.5))
model.add(Flatten())
model.add(Dense(256))
model.add(Activation('relu'))
model.add(Dropout(.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))
adam = Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-08)
model.compile(loss='mean_squared_error', optimizer=adam)
from cninit import init_model
init_model(model, X_train, Y_train)
h = model.fit(X_train, Y_train, batch_size=32, nb_epoch=200, show_accuracy=True, validation_data=(X_valid, Y_valid))
Y_predict = model.predict(X_valid)
print(Y_predict - Y_valid)
model.save_weights('model_weights.h5')
model.to_json('model.json')
| {
"repo_name": "bptripp/grasp-convnet",
"path": "py/model.py",
"copies": "1",
"size": "3409",
"license": "mit",
"hash": -7864330088695125000,
"line_mean": 31.1603773585,
"line_max": 116,
"alpha_frac": 0.6726312702,
"autogenerated": false,
"ratio": 2.9362618432385874,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.41088931134385875,
"avg_score": null,
"num_lines": null
} |
__author__ = 'bptripp'
from cnn_stimuli import get_image_file_list
import cPickle as pickle
import time
import numpy as np
import matplotlib.pyplot as plt
from alexnet import preprocess, load_net, load_vgg
def excess_kurtosis(columns):
m = np.mean(columns, axis=0)
sd = np.std(columns, axis=0)
result = np.zeros(columns.shape[1])
for i in range(columns.shape[1]):
column = columns[:,i]
d = column - m[i]
result[i] = np.sum(d**4) / columns.shape[0] / sd[i]**4 - 3
return result
# Copying these two functions from Salman's repo,
# ObjectSelectivity/sparseness.py and ObjectSelectivity/kurtosis_selectivity_profile.py
def calculate_kurtosis(rates_per_object):
"""
Given an array of firing rates of the neuron to objects, return the sparseness metric
Kurtosis (actually excess kurtosis) of the neuron as defined in:
[1] Lehky, S. R., Kiani, R., Esteky, H., & Tanaka, K. (2011). Statistics of
visual responses in primate inferotemporal cortex to object stimuli.
Journal of Neurophysiology, 106(3), 1097-117.
Kurtosis = (sum (Ri - Rmean)**4 / (n*sigma**4)) - 3
:param rates_per_object: array of firing rates of the neuron to multiple objects.
:return: kurtosis sparseness.
This is defined outside the class as it is used by other selectivity profiles.
"""
n = np.float(rates_per_object.shape[0])
rates_mean = np.mean(rates_per_object)
rates_sigma = np.std(rates_per_object)
kurtosis = np.sum((rates_per_object - rates_mean)**4) / (n * rates_sigma**4) - 3
# kurtosis2= np.sum((rates_per_object - rates_mean)**4) / n \
# / (np.sum((rates_per_object - rates_mean)**2) / n)** 2 - 3
return kurtosis
def activity_fraction(rates_per_object):
R = rates_per_object
n = len(rates_per_object)
return n/(n-1) * ( 1 - np.sum(R/n)**2 / np.sum(R**2/n) )
# num = 1 - (np.sum(R)/n)**2 / np.sum(R**2)/n
# den = 1 - 1/n
# return num / den
def plot_selectivity_and_sparseness(r_mat, font_size=10):
# plt.figure(figsize=)
# fig = plt.figure()
# print(fig.get_size_inches())
# f, ax_arr = plt.subplots(2, 1, sharex=True, figsize=(3.5,5))
f, ax_arr = plt.subplots(2, 1, sharex=False, figsize=(3,5))
# Single Neuron selectivities
n_neurons = r_mat.shape[0]
n_objs = r_mat.shape[1]
selectivities = np.zeros(n_neurons)
sparsenesses = np.zeros(n_objs)
for n_idx in np.arange(n_neurons):
rates = r_mat[n_idx, :]
selectivities[n_idx] = calculate_kurtosis(rates)
for o_idx in np.arange(n_objs):
rates = r_mat[:, o_idx]
sparsenesses[o_idx] = calculate_kurtosis(rates)
print(np.mean(selectivities))
print(np.mean(sparsenesses))
print('min selectivity: ' + str(np.min(selectivities)))
print('max selectivity: ' + str(np.max(selectivities)))
# Plot selectivities ------------------------------------------------
ax_arr[0].hist(np.clip(selectivities, -10, 25), bins=np.arange(-5, 850, step=1), color='red')
ax_arr[0].set_ylabel('frequency', fontsize=font_size)
ax_arr[0].set_xlabel('kurtosis', fontsize=font_size)
ax_arr[0].tick_params(axis='x', labelsize=font_size)
ax_arr[0].tick_params(axis='y', labelsize=font_size)
# ax_arr[0].set_xlim([0.1, 850])
ax_arr[0].annotate('mean=%0.2f' % np.mean(selectivities),
xy=(0.55, 0.98),
xycoords='axes fraction',
fontsize=font_size,
horizontalalignment='left',
verticalalignment='top')
ax_arr[0].annotate('med.=%0.2f' % np.median(selectivities),
xy=(0.55, 0.88),
xycoords='axes fraction',
fontsize=font_size,
horizontalalignment='left',
verticalalignment='top')
ax_arr[0].annotate('n=%d' % len(selectivities),
xy=(0.55, 0.78),
xycoords='axes fraction',
fontsize=font_size,
horizontalalignment='left',
verticalalignment='top')
ax_arr[0].annotate('single-neuron',
xy=(0.01, 0.98),
xycoords='axes fraction',
fontsize=font_size,
horizontalalignment='left',
verticalalignment='top')
# ax_arr[0].set_ylim([0, 40])
# ax_arr[0].set_xlim([0, 200])
# ax_arr[0].set_ylim([0, 130])
# ax_arr[0].set_xscale('log')
# Plot sparsenesses ------------------------------------------------
ax_arr[1].hist(np.clip(sparsenesses, -10, 60), bins=np.arange(-5, 850, step=3))
ax_arr[1].set_ylabel('frequency', fontsize=font_size)
ax_arr[1].set_xlabel('kurtosis', fontsize=font_size)
ax_arr[1].tick_params(axis='x', labelsize=font_size)
ax_arr[1].tick_params(axis='y', labelsize=font_size)
ax_arr[1].annotate('mean=%0.2f' % np.mean(sparsenesses),
xy=(0.55, 0.98),
xycoords='axes fraction',
fontsize=font_size,
horizontalalignment='left',
verticalalignment='top')
ax_arr[1].annotate('med.=%0.2f' % np.median(sparsenesses),
xy=(0.55, 0.88),
xycoords='axes fraction',
fontsize=font_size,
horizontalalignment='left',
verticalalignment='top')
ax_arr[1].annotate('n=%d' % len(sparsenesses),
xy=(0.55, 0.78),
xycoords='axes fraction',
fontsize=font_size,
horizontalalignment='left',
verticalalignment='top')
ax_arr[1].annotate('population',
xy=(0.01, 0.98),
xycoords='axes fraction',
fontsize=font_size,
horizontalalignment='left',
verticalalignment='top')
ax_arr[0].set_xlim([-2, 26])
ax_arr[1].set_xlim([-2, 62])
# ax_arr[1].set_ylim([0, 300])
plt.tight_layout()
# ax_arr[1].set_xscale('log')
if False:
with open('face-preference-alexnet-0.pkl', 'rb') as file:
alexnet0 = pickle.load(file)
with open('face-preference-alexnet-1.pkl', 'rb') as file:
alexnet1 = pickle.load(file)
with open('face-preference-alexnet-2.pkl', 'rb') as file:
alexnet2 = pickle.load(file)
with open('face-preference-vgg-0.pkl', 'rb') as file:
vgg0 = pickle.load(file)
with open('face-preference-vgg-1.pkl', 'rb') as file:
vgg1 = pickle.load(file)
with open('face-preference-vgg-2.pkl', 'rb') as file:
vgg2 = pickle.load(file)
edges = np.linspace(-5, 5, 21)
plt.figure(figsize=(8,4.5))
plt.subplot(2,3,1)
plt.hist(alexnet2, edges)
plt.ylabel('AlexNet Unit Count', fontsize=16)
plt.title('output-2', fontsize=16)
plt.subplot(2,3,2)
plt.hist(alexnet1, edges)
plt.title('output-1', fontsize=16)
plt.subplot(2,3,3)
plt.hist(alexnet0, edges)
plt.title('output', fontsize=16)
plt.subplot(2,3,4)
plt.hist(vgg2, edges, color='g')
plt.ylabel('VGG Unit Count', fontsize=16)
plt.subplot(2,3,5)
plt.hist(vgg1, edges, color='g')
plt.xlabel('Preference for Face Images', fontsize=16)
plt.subplot(2,3,6)
plt.hist(vgg0, edges, color='g')
plt.tight_layout(pad=0.05)
plt.savefig('../figures/selectivity-faces.eps')
plt.show()
if False:
use_vgg = True
remove_level = 2
if use_vgg:
model = load_vgg(weights_path='../weights/vgg16_weights.h5', remove_level=remove_level)
else:
model = load_net(weights_path='../weights/alexnet_weights.h5', remove_level=remove_level)
image_files = get_image_file_list('./images/lehky-processed/', 'png', with_path=True)
im = preprocess(image_files, use_vgg=use_vgg)
print(image_files)
mainly_faces = [197]
mainly_faces.extend(range(170, 178))
mainly_faces.extend(range(181, 196))
mainly_faces.extend(range(203, 214))
mainly_faces.extend(range(216, 224))
faces_major = [141, 142, 165, 169, 179, 196, 214, 215, 271]
faces_major.extend(range(144, 147))
faces_major.extend(range(157, 159))
faces_present = [131, 143, 178, 180, 198, 230, 233, 234, 305, 306, 316, 372, 470]
faces_present.extend(range(134, 141))
faces_present.extend(range(147, 150))
faces_present.extend(range(155, 157))
faces_present.extend(range(161, 165))
faces_present.extend(range(365, 369))
faces_present.extend(faces_major)
faces_present.extend(mainly_faces)
faces_ind = []
for i in range(len(image_files)):
for j in range(len(mainly_faces)):
if str(mainly_faces[j]) + '.' in image_files[i]:
faces_ind.append(i)
no_faces_ind = []
for i in range(len(image_files)):
has_face = False
for j in range(len(faces_present)):
if str(faces_present[j]) + '.' in image_files[i]:
has_face = True
if not has_face:
no_faces_ind.append(i)
# print(faces_ind)
# print(no_faces_ind)
start_time = time.time()
out = model.predict(im)
print(out.shape)
f = out[faces_ind,:]
nf = out[no_faces_ind,:]
print(f.shape)
print(nf.shape)
face_preference = np.mean(f, axis=0) - np.mean(nf, axis=0)
vf = np.var(f, axis=0) + 1e-3 # small constant in case zero variance due to lack of response
vnf = np.var(nf, axis=0) + 1e-3
d_prime = face_preference / np.sqrt((vf + vnf)/2)
network_name = 'vgg' if use_vgg else 'alexnet'
with open('face-preference-' + network_name + '-' + str(remove_level) + '.pkl', 'wb') as file:
pickle.dump(d_prime, file)
print(d_prime)
plt.hist(d_prime)
plt.show()
if True:
use_vgg = False
remove_level = 1
if use_vgg:
model = load_vgg(weights_path='../weights/vgg16_weights.h5', remove_level=remove_level)
else:
model = load_net(weights_path='../weights/alexnet_weights.h5', remove_level=remove_level)
# model = load_net(weights_path='../weights/alexnet_weights.h5')
image_files = get_image_file_list('./images/lehky-processed/', 'png', with_path=True)
im = preprocess(image_files, use_vgg=use_vgg)
start_time = time.time()
out = model.predict(im)
print('prediction time: ' + str(time.time() - start_time))
# with open('lehky.pkl', 'wb') as file:
# pickle.dump(out, file)
# with open('lehky.pkl', 'rb') as file:
# out = pickle.load(file)
n = 674
# use first n or n with greatest responses
if False:
rect = np.maximum(0, out[:,:n])
else:
maxima = np.max(out, axis=0)
ind = np.zeros(n, dtype=int)
c = 0
i = 0
while c < n:
if maxima[i] > 2:
ind[c] = i
c = c + 1
i = i + 1
# ind = (-maxima).argsort()[:n]
rect = np.maximum(0, out[:,ind])
selectivity = excess_kurtosis(rect)
sparseness = excess_kurtosis(rect.T)
print(np.mean(selectivity))
print(np.mean(sparseness))
print(np.max(selectivity))
print(np.max(sparseness))
plot_selectivity_and_sparseness(rect.T, 11)
network_name = 'vgg' if use_vgg else 'alexnet'
plt.savefig('../figures/selectivity-' + network_name + '-' + str(remove_level) + '-talk.eps')
plt.show()
if False:
plt.figure(figsize=(4,3.8))
plt.scatter(3.5, 12.51, c='k', marker='x', s=40, label='IT') # from Lehky et al. Fig 4A and 4B
selectivity_alexnet = [10.53, 28.59, 31.44]
sparseness_alexnet = [4.04, 8.85, 6.61]
selectivity_vgg = [26.79, 14.44, 34.65]
sparseness_vgg = [6.59, 3.40, 3.54]
plt.scatter([10.53, 28.59, 31.44], [4.04, 8.85, 6.61], c='b', marker='o', s=30, label='Alexnet')
plt.scatter([26.79, 14.44, 34.65], [6.59, 3.40, 3.54], c='g', marker='s', s=45, label='VGG-16')
plt.plot([0, 40], [0, 40], 'k')
plt.xlim([0,38])
plt.ylim([0,38])
gap = 0.4
plt.text(3.5+gap, 9.61+gap+.05, 'IT')
plt.text(selectivity_alexnet[0]+gap, sparseness_alexnet[0]+gap, 'out')
plt.text(selectivity_alexnet[1]+gap, sparseness_alexnet[1]+gap, 'out-1')
plt.text(selectivity_alexnet[2]+gap, sparseness_alexnet[2]+gap, 'out-2')
plt.text(selectivity_vgg[0]+gap, sparseness_vgg[0]+gap, 'out')
plt.text(selectivity_vgg[1]+gap, sparseness_vgg[1]+gap, 'out-1')
plt.text(selectivity_vgg[2]+gap, sparseness_vgg[2]+gap, 'out-2')
plt.xlabel('Selectivity')
plt.ylabel('Sparseness')
plt.tight_layout()
plt.savefig('../figures/cnn-selectivity.eps')
plt.show()
if False:
r_mat = rect.T
n_neurons = r_mat.shape[0]
activity_fractions = np.zeros(n_neurons)
for n_idx in np.arange(n_neurons):
rates = r_mat[n_idx, :]
activity_fractions[n_idx] = activity_fraction(rates)
print(activity_fractions)
plt.plot(activity_fractions)
plt.show()
rate = np.mean(rect,0)
# with open('activity-fraction.pkl', 'wb') as file:
# pickle.dump((ind, activity_fractions), file)
# bins = np.linspace(0, 1000, 501)
# plt.figure()
# plt.subplot(2,1,1)
# plt.hist(selectivity, bins)
# # plt.xlim([0, 100])
# # plt.ylim([0, 100])
# plt.subplot(2,1,2)
# plt.hist(sparseness, bins)
# # plt.xlim([0, 100])
# # plt.ylim([0, 100])
# plt.show()
#
# note: there is a NaN due to single kurtosis much less than gaussian
# print(np.corrcoef(np.mean(rect,0), np.log(selectivity+1)))
# plt.figure()
# plt.scatter(np.mean(rect,0), np.log(selectivity+1))
# plt.gca().set_xscale('log')
# plt.gca().set_yscale('log')
# plt.show()
#
# rate = np.mean(rect,0)
# with open('rate-vs-selectivity.pkl', 'wb') as file:
# pickle.dump((ind, rate, selectivity), file)
| {
"repo_name": "bptripp/it-cnn",
"path": "tuning/selectivity.py",
"copies": "1",
"size": "13980",
"license": "mit",
"hash": 7703437769836973000,
"line_mean": 32.3651551313,
"line_max": 100,
"alpha_frac": 0.5779685265,
"autogenerated": false,
"ratio": 3.051735428945645,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9111438104428167,
"avg_score": 0.0036531702034956226,
"num_lines": 419
} |
__author__ = 'bptripp'
from os import listdir, makedirs
from os.path import join, isfile, basename, exists
import numpy as np
from scipy import misc
import string
import matplotlib
import matplotlib.pyplot as plt
def get_image_file_list(source_path, extension, with_path=False):
if with_path:
result = [join(source_path, f) for f in listdir(source_path) if isfile(join(source_path, f)) and f.endswith(extension)]
else:
result = [f for f in listdir(source_path) if isfile(join(source_path, f)) and f.endswith(extension)]
return result
def alpha(i):
if i >= 26**2 or i < 0:
raise Exception('Can only handle indices from 0 to 675')
first = i/26
second = np.mod(i, 26)
return string.ascii_uppercase[first] + string.ascii_uppercase[second]
def process_lehky_files(source_path, dest_path):
"""
Reads raw files from Lehky et al. (2011) supplementary material and converts them to a good form
for AlexNet. Strips the border and embeds in larger gray image.
:param source_path: Where original images are
:param dest_path: Where processed images go
:return:
"""
border = 2
full_shape = [256,256,3]
background = 127
files = get_image_file_list(source_path, 'ppm')
if not exists(dest_path):
makedirs(dest_path)
for file in files:
image = misc.imread(join(source_path, file))
cropped = clean_lehky_image(image, border, background)
# cropped = image[border:(image.shape[0]-border),border:(image.shape[1]-border),:]
# cropped = np.maximum(255-cropped, 1) #without this there are various artefacts, don't know why
#
# for i in range(cropped.shape[0]):
# for j in range(cropped.shape[1]):
# distance = np.linalg.norm(cropped[i,j,0] - [background,background,background])
# if distance < 15:
# cropped[i,j,:] = background
full = np.zeros(full_shape)
full[:] = 127
corner = [full_shape[i]/2 - 1 - cropped.shape[i]/2 for i in range(2)]
full[corner[0]:corner[0]+cropped.shape[0],corner[1]:corner[1]+cropped.shape[1],:] = cropped
# plt.imshow(cropped)
# plt.imshow(full)
# plt.show()
misc.imsave(join(dest_path, file[:-4]+'.png'), full)
def clean_lehky_image(image, border, background):
cropped = image[border:(image.shape[0]-border),border:(image.shape[1]-border),:]
cropped = np.maximum(255-cropped, 1) #without this there are various artefacts, don't know why
cropped = 255 - cropped
for i in range(cropped.shape[0]):
for j in range(cropped.shape[1]):
distance = np.linalg.norm(cropped[i,j,0] - [background,background,background])
if distance < 15:
cropped[i,j,:] = background
return cropped
def make_orientations(source_image_file, orientations, dest_path):
if not exists(dest_path):
makedirs(dest_path)
source_name = basename(source_image_file)[:-4]
source_image = misc.imread(source_image_file)
scale = 100. / np.max(source_image.shape)
source_image = misc.imresize(source_image, scale)
full_dim = 256
ccr_dim = int(2*np.ceil(full_dim/2*2**.5)) # cover corners when rotated
# ccr_shape = [ccr_dim,ccr_dim]
background_colour = source_image[0,0,:]
big_image = np.tile(background_colour, [ccr_dim,ccr_dim,1])
corner = [ccr_dim/2-source_image.shape[0]/2, ccr_dim/2-source_image.shape[1]/2]
ss = source_image.shape
big_image[corner[0]:corner[0]+ss[0],corner[1]:corner[1]+ss[1],:] = source_image
# plt.imshow(background)
# plt.show()
# bg = np.round(np.mean(source_image[0:3,0:3,:]))
# print(bg)
# print(source_image[0:3,0:3,:])
# buffered = np.
for orientation in orientations:
rotated = misc.imrotate(big_image, orientation, interp='bilinear')
crop = (ccr_dim - full_dim)/2
cropped = rotated[crop:-crop,crop:-crop,:]
# plt.imshow(cropped)
# plt.show()
misc.imsave(join(dest_path, source_name + alpha(int(orientation)) + '.png'), cropped)
def add_borders(source_path, dest_path, scale=.2, dim=256, extension='png'):
if not exists(dest_path):
makedirs(dest_path)
files = get_image_file_list(source_path, extension)
for file in files:
image = misc.imread(join(source_path, file), mode='RGB')
image = misc.imresize(image, scale)
full = np.zeros((dim,dim,3), dtype=image.dtype)
full[:] = 255
corner = [dim/2 - 1 - image.shape[i]/2 for i in range(2)]
full[corner[0]:corner[0]+image.shape[0],corner[1]:corner[1]+image.shape[1],:] = image
# plt.figure()
# plt.subplot(2,1,1)
# plt.imshow(image)
# plt.subplot(2,1,2)
# plt.imshow(full)
# plt.show()
misc.imsave(join(dest_path, file), full)
def make_sizes(source_image_file, scales, dest_path):
if not exists(dest_path):
makedirs(dest_path)
# print(source_image_file)
source_name = basename(source_image_file)[:-4]
source_image = misc.imread(source_image_file)
background_colour = source_image[0,0,:]
dim = 256
for i in range(len(scales)):
result = np.tile(background_colour, [dim,dim,1])
scaled = misc.imresize(source_image, scales[i])
if scaled.shape[0] > dim:
trim = int((scaled.shape[0]-dim+1)/2)
scaled = scaled[trim:-trim,:,:]
if scaled.shape[1] > dim:
trim = int((scaled.shape[1]-dim+1)/2)
scaled = scaled[:,trim:-trim,:]
# print(scales[i])
# print(scaled.shape)
c = int(np.floor((dim-scaled.shape[0])/2)), int(np.floor((dim-scaled.shape[1])/2)) #corner
result[c[0]:c[0]+scaled.shape[0],c[1]:c[1]+scaled.shape[1]] = scaled
misc.imsave(join(dest_path, source_name + alpha(i) + '.png'), result)
# plt.imshow(result)
# plt.show()
def make_positions(source_image_file, scale, offsets, dest_path):
if not exists(dest_path):
makedirs(dest_path)
source_name = basename(source_image_file)[:-4]
source = misc.imread(source_image_file)
source = misc.imresize(source, scale)
background_colour = source[0,0,:]
dim = 256
for i in range(len(offsets)):
result = np.tile(background_colour, [dim,dim,1])
top = (dim-source.shape[0])/2
bottom = top+source.shape[0]
left = (dim-source.shape[1])/2+offsets[i]
right = left + source.shape[1]
section = source[:,np.maximum(0,-left):-1-np.maximum(0,right-dim),:]
result[top:bottom,np.maximum(0,left):np.minimum(dim-1,right-1),:] = section
misc.imsave(join(dest_path, source_name + alpha(i) + '.png'), result)
# plt.imshow(result)
# plt.show()
def make_positions_schwartz(source_image_file, offset, dest_path, scale=1):
if not exists(dest_path):
makedirs(dest_path)
source_name = basename(source_image_file)[:-4]
source = misc.imread(source_image_file)
source = misc.imresize(source, scale)
background_colour = source[0,0,:]
dim = 256
hor_offsets = [-offset, offset, 0, 0, 0]
ver_offsets = [0, 0, -offset, offset, 0]
for i in range(len(hor_offsets)):
result = np.tile(background_colour, [dim,dim,1])
top = (dim-source.shape[0])/2+ver_offsets[i]
bottom = top+source.shape[0]
left = (dim-source.shape[1])/2+hor_offsets[i]
right = left + source.shape[1]
section = source[:,np.maximum(0,-left):-1-np.maximum(0,right-dim),:]
result[top:bottom,np.maximum(0,left):np.minimum(dim-1,right-1),:] = section
misc.imsave(join(dest_path, source_name + alpha(i) + '.png'), result)
# plt.imshow(result)
# plt.show()
def make_occlusions(dest_path, shape_colour=[255,255,255], motion=False):
def make_background():
return 1 + 254*np.tile(np.random.randint(0, 2, [256,256,1]), [1,1,3])
# can't see how to extract pixels from image on mac, so drawing lines manually
def draw_line(image, p1, p2, width):
left = int(max(0, min(p1[1]-width, p2[1]-width)))
right = int(min(image.shape[1]-1, max(p1[1]+width, p2[1]+width)))
top = int(max(0, min(p1[0]-width, p2[0]-width)))
bottom = int(min(image.shape[1]-1, max(p1[0]+width, p2[0]+width)))
a = p1[0]-p2[0]
b = p2[1]-p1[1]
c = -a*p1[1] - b*p1[0]
for i in range(top, bottom):
for j in range(left, right):
if p1[0] == p2[0]: #horizontal
d = abs(i-p1[0])
elif p1[1] == p2[1]: #vertical
d = abs(j-p1[1])
else:
d = abs(a*j + b*i + c) / (a**2 + b**2)**.5
val = 255
if d < width:
# image[i,j,:] = 255
image[i,j,:] = shape_colour
elif d - width < 1:
image[i,j,:] = (d-width)*image[i,j,:] + (1-d+width)*np.array(shape_colour, dtype=int) #[val,val,val]
def draw_contour(image, x, y, width):
for i in range(len(x)-1):
draw_line(image, (x[i],y[i]), (x[i+1],y[i+1]), width)
def occlude(image, p):
block_dim = 8
original_image = image.copy()
for i in range(image.shape[0]/block_dim):
for j in range(image.shape[1]/block_dim):
if np.random.rand() < p:
if not motion:
image[block_dim*i:block_dim*(i+1), block_dim*j:block_dim*(j+1), :] = 255
else:
# simulate motion of ~1.5 degrees diagonally by moving down and right 20 pixels
# simulate transience of occlusion at each point with transparency
opacity = .05
for k in range(20):
top = block_dim*i+k
bottom = min(block_dim*(i+1)+k,image.shape[0])
left = block_dim*j+k
right = min(block_dim*(j+1)+k, image.shape[1])
change = opacity * (255 - original_image[top:bottom, left:right, :])
image[top:bottom, left:right, :] = image[top:bottom, left:right, :] + change
# image[top:bottom, left:right, :] \
# = (1-opacity) * image[top:bottom, left:right, :] \
# + opacity * 255
def save_occlusions(name, x, y, line_width):
d = join(dest_path, name)
if not exists(d):
makedirs(d)
# x, y: lists of coordinates of shape outline to plot
percent_occlusion = [0, 20, 50, 90, 100]
for p in percent_occlusion:
for rep in range(10):
image = make_background()
draw_contour(image, x, y, line_width)
occlude(image, p/100.)
# the 99 is a hack to make the files load in the expected order (not alphabetically)
misc.imsave(join(dest_path, name, name + str(np.minimum(p,99)) + '-' + str(rep) + '.png'), 255-image)
# plt.imshow(image)
# plt.show()
angle = np.linspace(0, 2*np.pi)
save_occlusions('circle', 128+30*np.cos(angle), 128+30*np.sin(angle), 2)
angle = np.linspace(0, 2*np.pi, 13)
radii = [30-15*np.mod(i,2) for i in range(len(angle))]
save_occlusions('star', 128+radii*np.cos(angle), 128+radii*np.sin(angle), 2)
a,b = 108,148
save_occlusions('square', [a,b,b,a,a], [a,a,b,b,a], 2)
save_occlusions('triangle', 128+np.array([18,18,-18,18]), 128+np.array([-18,18,0,-18]), 2)
save_occlusions('strange', 128+np.array([20,20,10,10,-20,-20,-10,-10,0,0,10,10,20]), 128+np.array([-30,20,20,10,10,0,0,-20,-20,0,0,-30,-30]), 2)
save_occlusions('arrow', 128-1.25*np.array([30, 10, 10, -25, -25, 10, 10, 30]), 128+1.25*np.array([0, 18, 10, 10, -10, -10, -18, 0]), 2)
save_occlusions('h', 128-1.25*np.array([20, -20, -20, -5, -5, -20, -20, 20, 20, 5, 5, 20, 20]), 128-1.25*np.array([-15, -15, -5, -5, 5, 5, 15, 15, 5, 5, -5, -5, -15]), 2)
angle = np.linspace(0, 2*np.pi, 9)+np.pi/8
save_occlusions('stop', 128+38*np.cos(angle), 128+38*np.sin(angle), 2)
# circle_image = make_background()
# angle = np.linspace(0, 2*np.pi)
# draw_contour(circle_image, 128+20*np.cos(angle), 128+20*np.sin(angle), 3)
def make_clutters(source_path, dest_path):
if not exists(dest_path):
makedirs(dest_path)
makedirs(join(dest_path+'/top'))
makedirs(join(dest_path+'/bottom'))
makedirs(join(dest_path+'/pair'))
full_shape = [256,256,3]
background_colour = 127
files = get_image_file_list(source_path, 'ppm')
images = []
for file in files:
image = misc.imread(join(source_path, file))
images.append(clean_lehky_image(image, 2, background_colour))
tops = images[:4]
bottoms = images[4:]
corner_top_image = [66,99] #top left corner of top image
corner_bottom_image = [132,99] # top left corner of bottom image
def get_background():
background = np.zeros(full_shape)
background[:] = background_colour
return background
def add_image(background, image, corner):
background[corner[0]:corner[0]+image.shape[0], corner[1]:corner[1]+image.shape[1] ,:] = image
for i in range(len(tops)):
full = get_background()
add_image(full, tops[i], corner_top_image)
misc.imsave(join(dest_path+'/top', 'top' + str(i) + '.png'), full)
for i in range(len(bottoms)):
full = get_background()
add_image(full, bottoms[i], corner_bottom_image)
misc.imsave(join(dest_path+'/bottom', 'bottom' + str(i) + '.png'), full)
# all pairs
for i in range(len(tops)):
for j in range(len(bottoms)):
full = get_background()
add_image(full, tops[i], corner_top_image)
add_image(full, bottoms[j], corner_bottom_image)
misc.imsave(join(dest_path+'/pair', 'pair' + str(i) + '-' + str(j) + '.png'), full)
# full = np.zeros(full_shape)
# full[:] = 127
#
# full[corner_top_image[0]:corner_top_image[0]+images[i].shape[0],corner_top_image[1]:corner_top_image[1]+images[i].shape[1],:] = images[i]
# full[corner_bottom_image[0]:corner_bottom_image[0]+images[j].shape[0],corner_bottom_image[1]:corner_bottom_image[1]+images[j].shape[1],:] = images[j]
#
# plt.imshow(full)
# plt.show()
def make_3d(source_dir, dest_dir):
# crop and resize images appropriately
target_shape = [256,256,3]
source_files = get_image_file_list(source_dir, 'jpg')
for source_file in source_files:
im = misc.imread(join(source_dir, source_file))
excess = im.shape[1] - im.shape[0]
cropped = im[:,excess/2:-excess/2]
resized = misc.imresize(cropped, target_shape)
# print(im.shape)
# print(cropped.shape)
# print(resized.shape)
misc.imsave(join(dest_dir, source_file), resized)
# source = misc.imread(source_image_file)
if __name__ == '__main__':
# add_borders('./source-images/simplification/from', './images/simplification/from')
# add_borders('./source-images/simplification/to', './images/simplification/to')
add_borders('./source-images/simplification/other', './images/simplification/other', scale=.85)
# # print(get_image_file_list('./source-images/lehky', 'ppm'))
#
# print('Cleaning Lehky et al. images ...')
# process_lehky_files('./source-images/lehky',
# './images/lehky-processed')
#
# print('Making orientation stimuli ... ')
# make_orientations('./source-images/banana.png',
# np.linspace(0, 360, 91),
# './images/banana-rotations')
#
# make_orientations('./source-images/shoe.png',
# np.linspace(0, 360, 91),
# './images/shoe-rotations')
#
# make_orientations('./source-images/corolla.png',
# np.linspace(0, 360, 91),
# './images/corolla-rotations')
#
# make_orientations('./source-images/swiss_knife.jpg',
# np.linspace(0, 360, 91),
# './images/swiss-knife-rotations')
#
# make_orientations('./source-images/staple.png',
# np.linspace(0, 360, 91),
# './images/staple-rotations')
#
# print('Making clutter stimuli ... ')
# make_clutters('./source-images/clutter',
# './images/clutter')
#
# print('Making occlusion stimuli ... ')
# make_occlusions('./images/occlusions-black')
# make_occlusions('./images/occlusions-red', shape_colour=[0,255,255])
# Note in Kovacs et al, the shape was typically presented for 500ms, the occlusion
# pattern moved at 3deg/s, and shapes covered an area of about 10deg^2, so the
# occlusion pattern moved about half the shape height (diagonally down)
# make_occlusions('./images/occlusions-moving', motion=True)
#
# print('Making size tuning stimuli ... ')
# # schwartz_scales = [13**.5/28**.5, 1., 50**.5/28**.5]
# schwartz_scales = .5*np.array([13**.5/28**.5, 1., 50**.5/28**.5])
# make_sizes('./source-images/schwartz/f1.png',
# schwartz_scales,
# './images/scales/f1')
# make_sizes('./source-images/schwartz/f2.png',
# schwartz_scales,
# './images/scales/f2')
# make_sizes('./source-images/schwartz/f3.png',
# schwartz_scales,
# './images/scales/f3')
# make_sizes('./source-images/schwartz/f4.png',
# schwartz_scales,
# './images/scales/f4')
# make_sizes('./source-images/schwartz/f5.png',
# schwartz_scales,
# './images/scales/f5')
# make_sizes('./source-images/schwartz/f6.png',
# schwartz_scales,
# './images/scales/f6')
#
# scales = np.logspace(np.log10(.05), np.log10(1.2), 45)
# make_sizes('./source-images/corolla.png',
# scales,
# './images/scales/corolla')
#
# make_sizes('./source-images/shoe.png',
# scales,
# './images/scales/shoe')
#
# make_sizes('./source-images/banana.png',
# scales,
# './images/scales/banana')
#
# print('Making position tuning stimuli ... ')
# offsets = np.linspace(-75, 75, 150/5+1, dtype=int)
# make_positions('./source-images/shoe.png', .4,
# offsets,
# './images/positions/shoe')
#
# make_positions('./source-images/banana.png', .4,
# offsets,
# './images/positions/banana')
#
# make_positions('./source-images/corolla.png', .4,
# offsets,
# './images/positions/corolla')
#
# make_positions('./source-images/staple.png', .4,
# offsets,
# './images/positions/staple')
#
# From Schwartz et al., 5 degrees up, down, left right with stimulus 28**.5=5.3 degrees wide
# our stimuli ~2/3 * 56 pixels = 37, so we want shifts of 35 pixels
# Our new stimuli ~150pixels wide and we'll scale by .5, so say 71-pixel shift
# schwartz_offset = 35
# schwartz_scale = .4
# schwartz_offset = schwartz_offset = (5/5.3)*(schwartz_scale*150)
# make_positions_schwartz('./source-images/schwartz/f1.png',
# schwartz_offset,
# './images/positions/f1', scale=schwartz_scale)
# make_positions_schwartz('./source-images/schwartz/f2.png',
# schwartz_offset,
# './images/positions/f2', scale=schwartz_scale)
# make_positions_schwartz('./source-images/schwartz/f3.png',
# schwartz_offset,
# './images/positions/f3', scale=schwartz_scale)
# make_positions_schwartz('./source-images/schwartz/f4.png',
# schwartz_offset,
# './images/positions/f4', scale=schwartz_scale)
# make_positions_schwartz('./source-images/schwartz/f5.png',
# schwartz_offset,
# './images/positions/f5', scale=schwartz_scale)
# make_positions_schwartz('./source-images/schwartz/f6.png',
# schwartz_offset,
# './images/positions/f6', scale=schwartz_scale)
# make_3d('/Users/bptripp/code/salman-IT/salman/images/scooter',
# '/Users/bptripp/code/salman-IT/salman/images/scooter-cropped')
# make_3d('/Users/bptripp/code/salman-IT/salman/images/staple',
# '/Users/bptripp/code/salman-IT/salman/images/staple-cropped')
# make_3d('/Users/bptripp/code/salman-IT/salman/images/head',
# '/Users/bptripp/code/salman-IT/salman/images/head-cropped')
| {
"repo_name": "bptripp/it-cnn",
"path": "tuning/cnn_stimuli.py",
"copies": "1",
"size": "21255",
"license": "mit",
"hash": -6568319712443032000,
"line_mean": 38.9530075188,
"line_max": 174,
"alpha_frac": 0.5637261821,
"autogenerated": false,
"ratio": 3.1704952267303104,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.42342214088303104,
"avg_score": null,
"num_lines": null
} |
__author__ = 'bptripp'
from os import listdir
from os.path import isfile, join
import cPickle
import numpy as np
import scipy
from keras.models import Sequential
from keras.layers.core import Dense, Flatten, Dropout, Activation
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.optimizers import Adam
from keras.models import model_from_json
from keras.regularizers import activity_l2
num_outputs = 250
def merge_data(rel_dir):
image_filenames = []
neuron_metrics = []
for f in listdir(rel_dir):
rel_filename = join(rel_dir, f)
if isfile(rel_filename) and f.endswith('.pkl') and not f == 'neuron-points.pkl':
object_name = f[:-11]
print('Processing ' + object_name)
with open(rel_filename) as rel_file:
target_indices, target_points, object_eye_points, object_eye_angles, neuron_metrics_for_object = cPickle.load(rel_file)
s = neuron_metrics_for_object.shape
for i in range(s[0]): #loop through target points
for j in range(s[1]): #loop through eye perspectives
image_filename = object_name + '-' + str(i) + '-' + str(j) + '.png'
image_filenames.append(image_filename)
neuron_metrics.append(neuron_metrics_for_object[i,j,:])
with open('perspective-data.pkl', 'wb') as f:
cPickle.dump((image_filenames, np.array(neuron_metrics)), f)
def get_model():
model = Sequential()
model.add(Convolution2D(64, 7, 7, input_shape=(1,80,80), init='glorot_normal', border_mode='same', activity_regularizer=activity_l2(0.000001)))
model.add(Activation('relu'))
model.add(Convolution2D(64, 3, 3, init='glorot_normal', border_mode='same', activity_regularizer=activity_l2(0.000001)))
model.add(Activation('relu'))
# model.add(Dropout(.5))
model.add(Convolution2D(64, 3, 3, init='glorot_normal', border_mode='same', activity_regularizer=activity_l2(0.000001)))
model.add(Activation('relu'))
model.add(MaxPooling2D((2,2)))
# model.add(Dropout(.5))
model.add(Flatten())
model.add(Dense(256, activity_regularizer=activity_l2(0.000001)))
model.add(Activation('relu'))
model.add(Dropout(.5))
model.add(Dense(1024, activity_regularizer=activity_l2(0.000001)))
model.add(Activation('relu'))
model.add(Dropout(.5))
model.add(Dense(num_outputs))
adam = Adam(lr=0.000001, beta_1=0.9, beta_2=0.999, epsilon=1e-08)
model.compile(loss='mse', optimizer=adam)
return model
def load_model(weights_file='p-model-weights.h5'):
model = model_from_json(open('p-model-architecture-big-reg.json').read())
model.load_weights(weights_file)
adam = Adam(lr=0.000001, beta_1=0.9, beta_2=0.999, epsilon=1e-08)
model.compile(loss='mse', optimizer=adam)
return model
def load_data(data_file):
with open(data_file, 'rb') as f:
image_filenames, neuron_metrics = cPickle.load(f)
return image_filenames, neuron_metrics[:,:num_outputs]
def check_data():
image_filenames, neuron_metrics = load_data('perspective-data-small.pkl')
print(len(image_filenames))
print(neuron_metrics.shape)
print(image_filenames[0])
print(neuron_metrics[0])
print(np.min(neuron_metrics))
print(np.max(neuron_metrics))
print(np.mean(neuron_metrics))
print(np.std(neuron_metrics))
def get_input(image_dir, image_file):
image = scipy.misc.imread(join(image_dir, image_file))
return np.array(image / 255.0)
def get_XY(image_dir, image_filenames, neuron_metrics, indices):
X = []
Y = []
for ind in indices:
X.append(get_input(image_dir, image_filenames[ind])[np.newaxis,:])
Y.append(neuron_metrics[ind])
return np.array(X), np.array(Y)
def train_model(model, data_file, image_dir, train_indices, valid_indices):
image_filenames, neuron_metrics = load_data(data_file)
print(len(image_filenames))
X_valid, Y_valid = get_XY(image_dir, image_filenames, neuron_metrics, valid_indices)
def generate_XY():
while 1:
batch_X = []
batch_Y = []
for i in range(32):
ind = train_indices[np.random.randint(len(train_indices))]
X = get_input(image_dir, image_filenames[ind])
Y = neuron_metrics[ind]
batch_X.append(X[np.newaxis,:])
batch_Y.append(Y)
yield (np.array(batch_X), np.array(batch_Y))
for i in range(10,13):
h = model.fit_generator(generate_XY(),
samples_per_epoch=8192, nb_epoch=100,
validation_data=(X_valid, Y_valid))
with file('p-history-big-reg-' + str(i) + '.pkl', 'wb') as f:
cPickle.dump(h.history, f)
json_string = model.to_json()
open('p-model-architecture-big-reg.json', 'w').write(json_string)
model.save_weights('p-model-weights-big-reg-' + str(i) + '.h5', overwrite=True)
def predict(model, image_dir, data_file, indices):
image_filenames, neuron_metrics = load_data(data_file)
X, Y = get_XY(image_dir, image_filenames, neuron_metrics, indices)
return Y, model.predict(X, batch_size=32, verbose=0)
if __name__ == '__main__':
# merge_data('/Volumes/TrainingData/grasp-conv/data/relative-small/')
# check_data()
valid_indices = np.arange(0, 50000, 100)
s = set(valid_indices)
train_indices = [x for x in range(70000) if x not in s]
#model = get_model()
model = load_model(weights_file='p-model-weights-big-reg-9.h5')
train_model(model,
'perspective-data-big.pkl',
'../../grasp-conv/data/eye-perspectives',
train_indices,
valid_indices)
#model = load_model(weights_file='p-model-weights-big-9.h5')
#targets, predictions = predict(model,
# '../../grasp-conv/data/eye-perspectives',
# 'perspective-data-big.pkl',
# valid_indices)
#with open('perspective-predictions-big-9.pkl', 'wb') as f:
# cPickle.dump((targets, predictions), f)
| {
"repo_name": "bptripp/grasp-convnet",
"path": "py/perspective_model.py",
"copies": "1",
"size": "6118",
"license": "mit",
"hash": -4846606596169325000,
"line_mean": 34.5697674419,
"line_max": 147,
"alpha_frac": 0.6312520432,
"autogenerated": false,
"ratio": 3.292787944025834,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4424039987225834,
"avg_score": null,
"num_lines": null
} |
__author__ = 'bptripp'
from os import listdir
from os.path import isfile, join
import time
import numpy as np
import matplotlib.pyplot as plt
import cPickle
from PIL import Image
from scipy.optimize import bisect
from quaternion import angle_between_quaterions, to_quaternion
def get_random_points(n, radius, surface=False):
point_directions = np.random.randn(3, n)
norms = np.sum(point_directions**2, axis=0)**.5
points = radius * point_directions / norms
if not surface:
# points = points * np.random.rand(n)**(1./3.)
palm = .035 #TODO: whoops, this is in metres, not fraction of radius
points = points * (palm + (1-palm)*np.random.rand(n))
return points
def get_random_angles(n, std=np.pi/8.):
"""
:param n: Number of angles needed
:return: Random angles in restricted ranges, meant as deviations in perspective around
looking staight at something.
"""
angles = std*np.random.randn(3, n)
angles[2,:] = 2*np.pi*np.random.rand(1, n)
return angles
def get_rotation_matrix(point, angle):
"""
:param point: Location of camera
:param angle: Not what you expect: this is a list of angles relative to looking
at (0,0,0), about world-z (azimuth), camera-y (elevation), and camera-z (roll).
Random samples are produced by get_random_angles().
:return: just what you expect
"""
z = -point #location of (0,0,0) relative to point
alpha = np.arctan(z[1]/z[0])
if z[0] < 0: alpha = alpha + np.pi
if alpha < 0: alpha = alpha + 2.*np.pi
alpha = alpha + angle[0]
# rotate by alpha about z
Rz = np.array([[np.cos(alpha), -np.sin(alpha), 0], [np.sin(alpha), np.cos(alpha), 0], [0, 0, 1]])
# find elevation in new coordinates
beta = -np.arctan(np.sqrt(z[0]**2+z[1]**2)/z[2])
if z[2] < 0: beta = beta + np.pi
if beta < 0: beta = beta + 2.*np.pi
beta = beta + angle[1]
# rotate by beta about y
Ry = np.array([[np.cos(beta), 0, -np.sin(beta)], [0, 1, 0], [np.sin(beta), 0, np.cos(beta)]])
gamma = angle[2]
Rz2 = np.array([[np.cos(-gamma), -np.sin(-gamma), 0], [np.sin(-gamma), np.cos(-gamma), 0], [0, 0, 1]])
return np.dot(Rz, np.dot(Ry, Rz2))
def check_rotation_matrix(scatter=False):
from mpl_toolkits.mplot3d import axes3d, Axes3D
n = 6
points = get_random_points(n, 2)
angles = get_random_angles(n)
# point = np.array([1,1e-6,1e-6])
# point = np.array([1e-6,1,1e-6])
fig = plt.figure()
ax = fig.add_subplot(1,1,1,projection='3d')
for i in range(points.shape[1]):
point = points[:,i]
angle = angles[:,i]
if not scatter:
angle[0] = 0
angle[1] = 0
R = get_rotation_matrix(point, angle)
ax.scatter(0, 0, 0, color='b')
ax.scatter(point[0], point[1], point[2], color='r')
x = np.dot(R, np.array([1,0,0]))
y = np.dot(R, np.array([0,1,0]))
z = np.dot(R, np.array([0,0,1]))
ax.plot([point[0],point[0]+x[0]], [point[1],point[1]+x[1]], [point[2],point[2]+x[2]], color='r')
ax.plot([point[0],point[0]+y[0]], [point[1],point[1]+y[1]], [point[2],point[2]+y[2]], color='g')
ax.plot([point[0],point[0]+z[0]], [point[1],point[1]+z[1]], [point[2],point[2]+z[2]], color='b')
plt.xlabel('x')
plt.ylabel('y')
plt.ylabel('z')
if not scatter:
plt.title('blue axes should point AT blue dot (zero)')
else:
plt.title('blue axes should point NEAR blue dot (zero)')
plt.show()
def check_depth_from_random_perspective():
from depthmap import loadOBJ, Display
filename = '../data/obj_files/24_bowl-02-Mar-2016-07-03-29.obj'
verts, faces = loadOBJ(filename)
# put vertical centre at zero
verts = np.array(verts)
minz = np.min(verts, axis=0)[2]
maxz = np.max(verts, axis=0)[2]
verts[:,2] = verts[:,2] - (minz+maxz)/2
n = 6
points = get_random_points(n, .25)
angles = get_random_angles(n)
point = points[:,0]
angle = angles[:,0]
rot = get_rotation_matrix(point, angle)
im_width = 80
d = Display(imsize=(im_width,im_width))
d.set_camera_position(point, rot, .5)
d.set_mesh(verts, faces)
depth = d.read_depth()
d.close()
X = np.arange(0, im_width)
Y = np.arange(0, im_width)
X, Y = np.meshgrid(X, Y)
from mpl_toolkits.mplot3d import axes3d, Axes3D
fig = plt.figure()
ax = fig.add_subplot(1,1,1,projection='3d')
ax.plot_wireframe(X, Y, depth)
ax.set_xlabel('x')
plt.show()
def find_vertical(point):
"""
Find new angle[2] so that camera-up points up. In terms of rotation matrix,
R[2,0] should be 0 (x-axis horizontal) and R[2,1] should be positive (pointing
up rather than down).
"""
def f(gamma):
return get_rotation_matrix(point, np.array([0, 0, gamma]))[2][0]
gamma = bisect(f, 0, np.pi)
# if get_rotation_matrix(point, np.array([0, 0, gamma]))[2][1] < 0:
if get_rotation_matrix(point, np.array([0, 0, gamma]))[2][1] > 0:
gamma = gamma + np.pi
return gamma
def check_find_vertical():
n = 3
points = get_random_points(n, .35, surface=True)
for i in range(n):
point = points[:,i]
gamma = find_vertical(point)
rot = get_rotation_matrix(point, np.array([0, 0, gamma]))
print(rot)
# if np.abs(rot[2,0] > 1e-6) or rot[2,1] < 0:
if np.abs(rot[2,0] > 1e-6) or rot[2,1] > 0:
print('error with gamma: ' + str(gamma) + ' should be 0: ' + str(rot[2,0]) + ' should be +ve: ' + str(rot[2,1]))
def plot_random_samples():
n = 1000
points = get_random_points(n, .25)
angles = get_random_angles(n)
from mpl_toolkits.mplot3d import axes3d, Axes3D
fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(1,2,1,projection='3d')
ax.scatter(points[0,:], points[1,:], points[2,:])
ax = fig.add_subplot(1,2,2,projection='3d')
ax.scatter(angles[0,:], angles[1,:], angles[2,:])
plt.show()
def get_perspectives(obj_filename, points, angles, im_width=80, near_clip=.25, far_clip=0.8, fov=45, camera_offset=.45, target_point=None):
from depthmap import loadOBJ, Display, get_distance
verts, faces = loadOBJ(obj_filename)
# put vertical centre at zero
verts = np.array(verts)
min_bounding_box = np.min(verts, axis=0)
max_bounding_box = np.max(verts, axis=0)
# set bounding box centre to 0,0,0
verts[:,0] = verts[:,0] - (min_bounding_box[0]+max_bounding_box[0])/2.
verts[:,1] = verts[:,1] - (min_bounding_box[1]+max_bounding_box[1])/2.
verts[:,2] = verts[:,2] - (min_bounding_box[2]+max_bounding_box[2])/2.
if target_point is not None:
verts[:,0] = verts[:,0] - target_point[0]
verts[:,1] = verts[:,1] - target_point[1]
verts[:,2] = verts[:,2] - target_point[2]
d = Display(imsize=(im_width,im_width))
d.set_perspective(fov=fov, near_clip=near_clip, far_clip=far_clip)
perspectives = np.zeros((points.shape[1],im_width,im_width), dtype='float32')
for i in range(points.shape[1]):
point = points[:,i]
angle = angles[:,i]
rot = get_rotation_matrix(point, angle)
d.set_camera_position(point, rot, camera_offset)
d.set_mesh(verts, faces)
depth = d.read_depth()
distance = get_distance(depth, near_clip, far_clip)
perspectives[i,:,:] = distance
d.close()
return perspectives
def process_directory(obj_dir, data_dir, n):
from os import listdir
from os.path import isfile, join
import time
for f in listdir(obj_dir):
obj_filename = join(obj_dir, f)
if isfile(obj_filename) and f.endswith('.obj'):
data_filename = join(data_dir, f[:-4] + '.pkl')
if isfile(data_filename):
print('Skipping ' + f)
else:
print('Processing ' + f)
start_time = time.time()
points = get_random_points(n, .15)
angles = get_random_angles(n, std=0)
print(angles)
perspectives = get_perspectives(obj_filename, points, angles)
f = open(data_filename, 'wb')
cPickle.dump((points, angles, perspectives), f)
f.close()
print(' ' + str(time.time()-start_time) + 's')
def process_eye_directory(obj_dir, data_dir, n):
#TODO: save image files here to allow random ordering during training
from os import listdir
from os.path import isfile, join
import time
for f in listdir(obj_dir):
obj_filename = join(obj_dir, f)
if isfile(obj_filename) and f.endswith('.obj'):
data_filename = join(data_dir, f[:-4] + '.pkl')
if isfile(data_filename):
print('Skipping ' + f)
else:
print('Processing ' + f)
start_time = time.time()
points = get_random_points(n, .35, surface=True) #.75m with offset
angles = np.zeros_like(points)
# Set camera-up to vertical via third angle (angle needed is always
# 3pi/4, but we'll find it numerically in case other parts of code
# change while we're not looking).
for i in range(n):
angles[2,i] = find_vertical(points[:,i])
perspectives = get_perspectives(obj_filename, points, angles, near_clip=.4, fov=30)
f = open(data_filename, 'wb')
cPickle.dump((points, angles, perspectives), f)
f.close()
print(' ' + str(time.time()-start_time) + 's')
def check_maps(data_dir):
"""
Checks pkl files in given directory to see if any of the depth maps they contain
are empty.
"""
from os import listdir
from os.path import isfile, join
for f in listdir(data_dir):
data_filename = join(data_dir, f)
if isfile(data_filename) and f.endswith('.pkl'):
print('Checking ' + f)
f = open(data_filename, 'rb')
(points, angles, perspectives) = cPickle.load(f)
f.close()
for i in range(perspectives.shape[0]):
sd = np.std(perspectives[i,:,:].flatten())
if sd < 1e-3:
print(' map ' + str(i) + ' is empty')
def calculate_metrics(perspectives, im_width=80, fov=45.0, camera_offset=.45):
"""
:param perspectives: numpy array of depth images of object from gripper perspective
"""
asymmetry_scale = 13.0 #TODO: calculate from camera params (13 pixels is ~5cm with default params)
from heuristic import finger_path_template, calculate_grip_metrics
finger_path = finger_path_template(fov*np.pi/180., im_width, camera_offset)
collision_template = np.zeros_like(finger_path)
collision_template[finger_path > 0] = camera_offset + 0.033
# print(np.max(collision_template))
# print(np.max(finger_path))
# plt.imshow(collision_template)
# plt.show()
metrics = []
collisions = []
for perspective in perspectives:
intersections, qualities = calculate_grip_metrics(perspective, finger_path)
q1 = qualities[0]
q2 = qualities[1]
q3 = qualities[2]
if intersections[0] is None or intersections[2] is None:
a1 = 1
else:
a1 = ((intersections[0]-intersections[2])/asymmetry_scale)**2
if intersections[1] is None or intersections[2] is None:
a2 = 1
else:
a2 = ((intersections[1]-intersections[2])/asymmetry_scale)**2
m = np.minimum((q1+q2)/1.5, q3) / (1 + (q1*a1+q2*a2) / (q1+q2+1e-6))
collision = np.max(collision_template - perspective) > 0
collisions.append(collision)
# if collision:
# m = 0
metrics.append(m)
# plt.subplot(1,2,1)
# plt.imshow(perspective)
# plt.subplot(1,2,2)
# plt.imshow(np.maximum(0, finger_path-perspective))
# print(collision)
# print((a1,a2))
# print(intersections)
# print(qualities)
# print('metric: ' + str(m))
# plt.show()
# print((intersections, qualities))
return metrics, collisions
def get_quaternion_distance(points, angles):
"""
Get new representation of camera/gripper configurations as rotation quaternions and
distances from origin, rather than 3D points and rotations about axis pointing to origin.
"""
# print(points)
# print(angles)
quaternions = []
distances = []
for point, angle in zip(points.T, angles.T):
distances.append(np.linalg.norm(point))
quaternions.append(to_quaternion(get_rotation_matrix(point, angle)))
return np.array(quaternions), np.array(distances)
def smooth_metrics(quaternions, distances, metrics):
from interpolate import interpolate
smoothed = []
for i in range(len(metrics)):
# print(i)
interpolated = interpolate(quaternions[i], distances[i], quaternions, distances, metrics,
sigma_d=.02, sigma_a=(16*np.pi/180))
smoothed.append(interpolated)
# print(interpolated - metrics[one])
return smoothed
def load_target_points(filename):
objects = []
indices = []
points = []
for line in open(filename, "r"):
vals = line.translate(None, '"\n').split(',')
assert len(vals) == 5
objects.append(vals[0])
indices.append(int(vals[1]))
points.append([float(vals[2]), float(vals[3]), float(vals[4])])
return objects, indices, points
def get_target_points_for_object(objects, indices, points, object):
indices_for_object = []
points_for_object = []
for o, i, p in zip(objects, indices, points):
if o == object:
indices_for_object.append(i)
points_for_object.append(p)
return np.array(indices_for_object), np.array(points_for_object)
def check_target_points():
objects, indices, points = load_target_points('../../grasp-conv/data/obj-points.csv')
print(objects)
print(indices)
print(points)
indices, points = get_target_points_for_object(objects, indices, points, '28_Spatula_final-11-Nov-2015-14-22-01.obj')
print(indices)
print(points)
def check_metrics():
# points, angles, metrics, collisions = calculate_metrics('../../grasp-conv/data/perspectives/28_Spatula_final-11-Nov-2015-14-22-01.pkl')
# with open('spatula-perspectives.pkl', 'wb') as f:
# cPickle.dump((points, angles, metrics, collisions), f)
with open('spatula-perspectives.pkl', 'rb') as f:
(points, angles, metrics, collisions) = cPickle.load(f)
metrics = np.array(metrics)
smoothed = smooth_metrics(points, angles, metrics)
with open('spatula-perspectives-smoothed.pkl', 'wb') as f:
cPickle.dump((points, angles, metrics, collisions, smoothed), f)
plt.hist(metrics, bins=50)
plt.show()
def make_grip_perspective_depths(obj_dir, data_dir, target_points_file, n=1000):
objects, indices, points = load_target_points(target_points_file)
for f in listdir(obj_dir):
obj_filename = join(obj_dir, f)
if isfile(obj_filename) and f.endswith('.obj'):
data_filename = join(data_dir, f[:-4] + '.pkl')
if isfile(data_filename):
print('Skipping ' + f)
else:
print('Processing ' + f)
target_indices, target_points = get_target_points_for_object(objects, indices, points, f)
start_time = time.time()
#TODO: is there any reason to make points & angles these the same or different across targets?
gripper_points = get_random_points(n, .15)
gripper_angles = get_random_angles(n, std=0)
perspectives = []
for target_point in target_points:
print(' ' + str(target_point))
p = get_perspectives(obj_filename, gripper_points, gripper_angles, target_point=target_point)
perspectives.append(p)
f = open(data_filename, 'wb')
cPickle.dump((gripper_points, gripper_angles, target_indices, target_points, perspectives), f)
f.close()
print(' ' + str(time.time()-start_time) + 's')
def make_metrics(perspective_dir, metric_dir):
"""
We'll store in separate pkl files per object to allow incremental processing, even through results
won't take much memory.
"""
for f in listdir(perspective_dir):
perspective_filename = join(perspective_dir, f)
if isfile(perspective_filename) and f.endswith('.pkl'):
metric_filename = join(metric_dir, f[:-4] + '-metrics.pkl')
if isfile(metric_filename):
print('Skipping ' + f)
else:
print('Processing ' + f)
start_time = time.time()
with open(perspective_filename) as perspective_file:
gripper_points, gripper_angles, target_indices, target_points, perspectives = cPickle.load(perspective_file)
print('unpickle: ' + str(time.time() - start_time))
quaternions, distances = get_quaternion_distance(gripper_points, gripper_angles)
collisions = []
free_smoothed = []
coll_smoothed = []
for p in perspectives: # one per target point
fm, c = calculate_metrics(p)
fm = np.array(fm)
c = np.array(c)
fs = smooth_metrics(quaternions, distances, fm)
cm = fm * (1-c)
cs = smooth_metrics(quaternions, distances, cm)
collisions.append(c)
free_smoothed.append(fs)
coll_smoothed.append(cs)
f = open(metric_filename, 'wb')
cPickle.dump((gripper_points, gripper_angles, target_indices, target_points,
collisions, free_smoothed, coll_smoothed), f)
f.close()
def make_eye_perspective_depths(obj_dir, data_dir, target_points_file, n=20):
all_objects, all_target_indices, all_target_points = load_target_points(target_points_file)
camera_offset=.45
near_clip=.6
far_clip=1.0
eye_points = []
eye_angles = []
objects = []
target_indices = []
target_points = []
for f in listdir(obj_dir):
obj_filename = join(obj_dir, f)
if isfile(obj_filename) and f.endswith('.obj'): #and int(f[0]) >= 0: #TODO: set f[0] range here
print('Processing ' + f)
ti, tp= get_target_points_for_object(all_objects, all_target_indices, all_target_points, f)
objects.append(f)
target_indices.append(ti)
target_points.append(tp)
start_time = time.time()
points = get_random_points(n, .35, surface=True) #.8m with offset
# points = np.array([[ 0.00001], [0.35], [0.00001]]) # TODO: bug with x=0 and with z=0
print(points)
angles = np.zeros_like(points)
eye_points.append(points)
eye_angles.append(angles)
# Set camera-up to vertical via third angle (angle needed is always
# 3pi/4, but we'll find it numerically in case other parts of code
# change while we're not looking).
for i in range(n):
angles[2,i] = find_vertical(points[:,i])
perspectives = []
for target_index, target_point in zip(ti, tp):
print(' ' + str(target_point))
perspectives = get_perspectives(obj_filename, points, angles,
near_clip=near_clip, far_clip=far_clip, camera_offset=camera_offset,
fov=30, target_point=target_point)
for i in range(len(perspectives)):
distance = perspectives[i]
rescaled_distance = np.maximum(0, (distance-camera_offset)/(far_clip-camera_offset))
imfile = data_dir + f[:-4] + '-' + str(target_index) + '-' + str(i) + '.png'
Image.fromarray((255.0*rescaled_distance).astype('uint8')).save(imfile)
print(' ' + str(time.time()-start_time) + 's')
data_filename = join(data_dir, 'eye-perspectives-murata.pkl')
f = open(data_filename, 'wb')
cPickle.dump((objects, target_indices, target_points, eye_points, eye_angles), f)
f.close()
def merge_eye_perspectives(data_dir):
# make_eye_perspective_depths mysteriously does not run all the way through, so I've
# done it in two parts which are merged here:
files = ['eye-perspectives1.pkl', 'eye-perspectives2.pkl']
objects = []
target_indices = []
target_points = []
eye_points = []
eye_angles = []
for file in files:
with open(join(data_dir, file), 'rb') as f:
o, ti, tp, ep, ea = cPickle.load(f)
objects.extend(o)
target_indices.extend(ti)
target_points.extend(tp)
eye_points.extend(ep)
eye_angles.extend(ea)
with open(join(data_dir, 'eye-perspectives.pkl'),'wb') as f:
cPickle.dump((objects, target_indices, target_points, eye_points, eye_angles), f)
def export_neuron_perspectives():
import csv
with open('../data/neuron-points.pkl', 'rb') as f:
neuron_points, neuron_angles = cPickle.load(f)
with open('neuron-perspectives.csv', 'wb') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
for point, angle in zip(neuron_points.T, neuron_angles.T):
R = get_rotation_matrix(point, angle)
row = list(point)
row.extend(R.flatten())
writer.writerow(row)
def export_eye_perspectives(eye_perspectives_file):
import csv
with open(eye_perspectives_file) as f:
objects, target_indices, target_points, eye_points, eye_angles = cPickle.load(f)
with open('eye-perspectives.csv', 'wb') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
for object, ep, ea, tp in zip(objects, eye_points, eye_angles, target_points):
print('Processing ' + object)
for target_point in tp:
for eye_point, eye_angle in zip(ep.T, ea.T):
eye_R = get_rotation_matrix(eye_point, eye_angle)
# row = [object]
row = []
row.extend(target_point)
row.extend(eye_point)
row.extend(eye_R.flatten())
writer.writerow(row)
def make_relative_metrics(eye_perspectives_file, metrics_dir, result_dir, n=500, neuron_points=None, neuron_angles=None):
from quaternion import difference_between_quaternions
from interpolate import interpolate
# each of these points/angles will correspond to an output neuron ...
if neuron_points is None or neuron_angles is None:
neuron_points = get_random_points(n, .15)
neuron_angles = get_random_angles(n, std=0)
with open(join(result_dir, 'neuron-points.pkl'), 'wb') as f:
cPickle.dump((neuron_points, neuron_angles), f)
neuron_quaternions, neuron_distances = get_quaternion_distance(neuron_points, neuron_angles)
with open(eye_perspectives_file) as f:
objects, target_indices, target_points, eye_points, eye_angles = cPickle.load(f)
for object, object_eye_points, object_eye_angles in zip(objects, eye_points, eye_angles):
print('Processing ' + object)
start_time = time.time()
eye_quaternions, eye_distances = get_quaternion_distance(object_eye_points, object_eye_angles)
metrics_file = join(metrics_dir, object[:-4] + '-metrics.pkl')
with open(metrics_file) as f:
gripper_points, gripper_angles, target_indices, target_points, collisions, free_smoothed, coll_smoothed = cPickle.load(f)
gripper_quaternions, gripper_distances = get_quaternion_distance(gripper_points, gripper_angles)
# note that for each object, gripper configs are the same relative to each target point
#TODO: do we want coll_smoothed instead / as well?
metrics = free_smoothed
# interpolate relative to each eye point
neuron_metrics_for_object = []
for target_index, target_metrics in zip(target_indices, metrics):
print(' target ' + str(target_index))
neuron_metrics_for_target = []
for eye_quaternion in eye_quaternions:
rel_quaternions = []
for gripper_quaternion in gripper_quaternions:
rel_quaternions.append(difference_between_quaternions(eye_quaternion, gripper_quaternion))
rel_quaternions = np.array(rel_quaternions)
#interpolate ...
neuron_metrics = []
for neuron_quaternion, neuron_distance in zip(neuron_quaternions, neuron_distances):
interpolated = interpolate(neuron_quaternion, neuron_distance, rel_quaternions, gripper_distances, target_metrics,
sigma_d=.02, sigma_a=(16*np.pi/180))
neuron_metrics.append(interpolated)
neuron_metrics_for_target.append(neuron_metrics)
neuron_metrics_for_object.append(neuron_metrics_for_target)
neuron_metrics_for_object = np.array(neuron_metrics_for_object)
result_file = join(result_dir, object[:-4] + '-neuron.pkl')
with open(result_file, 'wb') as f:
cPickle.dump((target_indices, target_points, object_eye_points, object_eye_angles, neuron_metrics_for_object), f)
print(' ' + str(time.time() - start_time) + 's')
def make_XY():
eye_image_files = []
metrics = []
return eye_image_files, metrics
if __name__ == '__main__':
# check_rotation_matrix(scatter=True)
# check_depth_from_random_perspective()
# plot_random_samples()
# check_find_vertical()
# check_target_points()
# check_metrics()
# make_grip_perspective_depths('../../grasp-conv/data/obj_tmp/',
# '../../grasp-conv/data/perspectives/',
# '../../grasp-conv/data/obj-points.csv')
# make_grip_perspective_depths('../../grasp-conv/data/obj_files/',
# '/Volumes/TrainingData/grasp-conv/data/perspectives/',
# '../../grasp-conv/data/obj-points.csv')
# make_eye_perspective_depths('../../grasp-conv/data/obj_tmp/',
# '../../grasp-conv/data/eye-tmp/',
# '../../grasp-conv/data/obj-points.csv')
make_eye_perspective_depths('../../grasp-conv/data/obj_files_murata/',
'../../grasp-conv/data/eye-perspectives-murata/',
'../../grasp-conv/data/obj-points-murata.csv',
n=1)
# make_eye_perspective_depths('../../grasp-conv/data/obj_files/',
# '/Volumes/TrainingData/grasp-conv/data/eye-perspectives/',
# '../../grasp-conv/data/obj-points.csv')
# merge_eye_perspectives('/Volumes/TrainingData/grasp-conv/data/eye-perspectives/')
# with open('/Volumes/TrainingData/grasp-conv/data/eye-perspectives/eye-perspectives.pkl','rb') as f:
# objects, target_indices, target_points, eye_points, eye_angles = cPickle.load(f)
# print(objects)
# print(target_indices)
# print(target_points)
# print(eye_angles)
# make_relative_metrics('/Volumes/TrainingData/grasp-conv/data/eye-perspectives/eye-perspectives.pkl',
# '/Volumes/TrainingData/grasp-conv/data/metrics/',
# '/Volumes/TrainingData/grasp-conv/data/relative/')
# export_neuron_perspectives()
# export_eye_perspectives('/Volumes/TrainingData/grasp-conv/data/eye-perspectives/eye-perspectives.pkl')
# import scipy
# image = scipy.misc.imread('../../grasp-conv/data/eye-tmp/1_Coffeecup_final-03-Mar-2016-18-50-40-0-7.png')
# plt.imshow(image)
# plt.show()
# with open('../../grasp-conv/data/eye-tmp/eye-perspectives.pkl') as f:
# objects, target_indices, target_points, eye_points, eye_angles = cPickle.load(f)
# print(objects)
# print(target_indices)
# print(target_points)
# print(np.array(eye_points))
# print(np.array(eye_angles))
# with open('spatula-perspectives.pkl', 'rb') as f:
# gripper_points, gripper_angles, target_indices, target_points, perspectives = cPickle.load(f)
# make_metrics('../../grasp-conv/data/perspectives/', '../../grasp-conv/data/metrics/')
# make_relative_metrics('../../grasp-conv/data/eye-tmp/eye-perspectives.pkl',
# '../../grasp-conv/data/metrics/',
# '../../grasp-conv/data/relative/')
# checking files look OK ...
# with open('../../grasp-conv/data/relative/neuron-points.pkl', 'rb') as f:
# neuron_points, neuron_angles = cPickle.load(f)
# print(neuron_angles.shape)
# with open('../../grasp-conv/data/relative/1_Coffeecup_final-03-Mar-2016-18-50-40-neuron.pkl', 'rb') as f:
# target_indices, target_points, object_eye_points, object_eye_angles, neuron_metrics_for_object = cPickle.load(f)
# print(neuron_metrics_for_object.shape)
# print(np.min(neuron_metrics_for_object))
# print(np.max(neuron_metrics_for_object))
# print(np.std(neuron_metrics_for_object))
# make_metrics('/Volumes/TrainingData/grasp-conv/data/perspectives/',
# '/Volumes/TrainingData/grasp-conv/data/metrics/')
# process_eye_directory('../../grasp-conv/data/obj_tmp/', '../../grasp-conv/data/eye-perspectives-tmp/', 100)
# process_directory('../data/obj_files/', '../data/perspectives/', 10)
# process_directory('../../grasp-conv/data/obj_tmp/', '../../grasp-conv/data/perspectives/', 5000)
# check_maps('../../grasp-conv/data/perspectives/')
| {
"repo_name": "bptripp/grasp-convnet",
"path": "py/perspective.py",
"copies": "1",
"size": "30382",
"license": "mit",
"hash": -3662520170638863000,
"line_mean": 37.3127364439,
"line_max": 141,
"alpha_frac": 0.5873543546,
"autogenerated": false,
"ratio": 3.4060538116591927,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9469955772366101,
"avg_score": 0.004690478778618361,
"num_lines": 793
} |
__author__ = 'bptripp'
from os.path import join
import cPickle
import matplotlib.pyplot as plt
import scipy.misc
import numpy as np
from perspective import get_rotation_matrix, get_random_points
def plot_correct_point_scatter():
n_points = 200
with open('../data/neuron-points.pkl', 'rb') as f:
neuron_points, neuron_angles = cPickle.load(f)
with open('perspective-data-small.pkl', 'rb') as f:
image_files, metrics = cPickle.load(f)
# print(metrics.shape)
index = 600
points = neuron_points[:,:n_points]
offsets = np.zeros_like(points)
for i in range(n_points):
r = get_rotation_matrix(neuron_points[:,i], neuron_angles[:,i])
offsets[:,i] = points[:,i] + np.dot(r, np.array([0,.005,0]))
from mpl_toolkits.mplot3d import axes3d, Axes3D
fig = plt.figure(figsize=(20,10))
ax = fig.add_subplot(1,2,1,projection='3d')
ax.scatter(points[0,:], points[1,:], points[2,:],
c=metrics[index,:n_points], cmap='autumn', depthshade=False)
ax.scatter(offsets[0,:], offsets[1,:], offsets[2,:],
c=metrics[index,:n_points], cmap='autumn', depthshade=False, s=10)
plt.subplot(1,2,2)
image = scipy.misc.imread(join('../../grasp-conv/data/eye-perspectives', image_files[index]))
plt.imshow(image)
plt.title(image_files[index])
plt.show()
# print(neuron_points[:,:n_points])
def plot_predictions():
# with open('perspective-predictions-better.pkl') as f:
with open('perspective-predictions-ray.pkl') as f:
targets, predictions = cPickle.load(f)
targets = targets.astype(float)
plt.figure(figsize=(9,6))
for i in range(25):
plt.subplot(5,5,i)
plt.scatter(targets[:,i], predictions[:,i], s=1)
cc = np.corrcoef(targets[:,i], predictions[:,i])
print(cc[0,1])
c = np.corrcoef(targets[:,i], predictions[:,i])[0,1]
plt.gca().axes.xaxis.set_ticks([])
plt.gca().axes.yaxis.set_ticks([])
print(c)
plt.tight_layout()
plt.show()
def plot_points_with_correlations():
with open('perspective-predictions-big-0.pkl') as f:
targets, predictions = cPickle.load(f)
n_points = targets.shape[1]
r = []
for i in range(n_points):
r.append(np.corrcoef(targets[:,i], predictions[:,i])[0,1])
with open('perspective-predictions-big-9.pkl') as f:
# with open('perspective-predictions-ray.pkl') as f:
targets, predictions = cPickle.load(f)
# targets = targets.astype(float)
r_better = []
for i in range(n_points):
r_better.append(np.corrcoef(targets[:,i], predictions[:,i])[0,1])
with open('../data/neuron-points.pkl', 'rb') as f:
neuron_points, neuron_angles = cPickle.load(f)
# from mpl_toolkits.mplot3d import axes3d, Axes3D
# fig = plt.figure()
# ax = fig.add_subplot(1,1,1,projection='3d')
# ax.scatter(neuron_points[0,:n_points], neuron_points[1,:n_points], neuron_points[2,:n_points],
# c=r, cmap='autumn', depthshade=False, s=40)
# plt.show()
angles_from_vertical = []
for i in range(n_points):
# hor = np.sqrt(neuron_points[0,i]**2 + neuron_points[1,i]**2)
# ver = neuron_points[2,i]
# angles_from_vertical.append(np.arctan(hor / ver))
norm = np.linalg.norm(neuron_points[:,i])
angles_from_vertical.append(np.arccos(neuron_points[2,i] / norm))
fig = plt.figure()
plt.scatter(angles_from_vertical, r, s=30, facecolors='none', edgecolors='r')
plt.scatter(angles_from_vertical, r_better, color='r', s=30)
plt.xlim([0,np.pi])
plt.ylim([0,1])
plt.tick_params(axis='both', labelsize=18)
plt.xlabel('angle between eye and hand (rad)', fontsize=18)
plt.ylabel('target-prediction correlation', fontsize=18)
plt.show()
def katsuyama_depths():
K = [[-0.1500, -0.1500],
[-0.1960, -0.0812],
[-0.2121, 0],
[-0.1960, 0.0812],
[-0.1500, 0.1500],
[-0.0812, 0.1960],
[0.0000, 0.2121],
[0.0812, 0.1960],
[0.1500, 0.1500],
[-0.2500, -0.2500],
[-0.3266, -0.1353],
[-0.3536, 0],
[-0.3266, 0.1353],
[-0.2500, 0.2500],
[-0.1353, 0.3266],
[0, 0.3536],
[0.1353, 0.3266],
[0.2500, 0.2500],
[0, 0]]
K = np.array(K)
# Original numbers for x and y in cm, whereas we want m. This requires multiplying
# by 10000, but such shapes are much sharper than objects, so we drop by 10x
print(K)
K = 1000. * K
depths = []
for i in range(K.shape[0]):
depths.append(katsuyama_depth(K[i,0], K[i,1]))
return np.array(depths)
def katsuyama_depth(K1, K2, c=.8, im_width=80, fov=30, near_clip=.6, far_clip=1):
# note their display was about 36 degrees
rads_per_pixel = (fov*np.pi/180.) / im_width
hor_angles = np.arange(-im_width/2+.5, im_width/2+.5, 1) * rads_per_pixel
ver_angles = hor_angles
ta = np.tan(hor_angles)**2
tb = np.tan(ver_angles)**2
# solve quadratic equation ...
b = -1
depth = np.zeros((len(ver_angles),len(hor_angles)))
for i in range(len(ver_angles)):
for j in range(len(hor_angles)):
a = .5 * (K1*tb[i] + K2*ta[j])
if np.abs(a) < 1e-6:
depth[i,j] = c
elif b**2 - 4*a*c < 0:
depth[i,j] = far_clip
else:
# we want the closer hit
depth[i,j] = (-b - np.sqrt(b**2 - 4*a*c)) / (2*a)
depth = np.minimum(far_clip, np.maximum(near_clip, depth))
return depth
def get_truncated_model(structure_file, weights_file, n_layers):
from keras.models import model_from_json
from keras.optimizers import Adam
from keras.models import Sequential
model = model_from_json(open(structure_file).read())
model.load_weights(weights_file)
print(str(len(model.layers)) + ' layers')
truncated = Sequential()
for i in range(n_layers):
truncated.add(model.layers[i])
adam = Adam(lr=0.000001, beta_1=0.9, beta_2=0.999, epsilon=1e-08)
truncated.compile(loss='mse', optimizer=adam)
return truncated
def save_katsutama_responses(structure_file, weights_file, n_layers):
model = get_truncated_model(structure_file, weights_file, n_layers)
x = katsuyama_depths()[:,np.newaxis,:,:]
responses = model.predict_on_batch(x)
print(responses.shape)
with open('katsuyama-' + str(n_layers) + '.pkl', 'wb') as f:
cPickle.dump(responses, f)
def save_murata_respones(structure_file, weights_file, n_layers):
from perspective_model import get_input
model = get_truncated_model(structure_file, weights_file, n_layers)
X = []
image_dir = '../../grasp-conv/data/eye-perspectives-murata/good'
X.append(get_input(image_dir, 'Cube 10 X 10 X 10-0-0.png'))
X.append(get_input(image_dir, 'Cylinder 45 X 5-0-0.png'))
X.append(get_input(image_dir, 'Ring - 15-0-0.png'))
X.append(get_input(image_dir, 'Sphere - 10-0-0.png'))
X = np.array(X)
X = X[:,np.newaxis,:,:]
responses = model.predict_on_batch(X)
with open('murata-' + str(n_layers) + '.pkl', 'wb') as f:
cPickle.dump(responses, f)
def plot_katsuyama_responses(n_layers):
with open('../data/katsuyama-' + str(n_layers) + '.pkl') as f:
data = cPickle.load(f)
if len(data.shape) == 4:
data = data[:,:,40,40]
print(data.shape)
data = data - data[18,:] #18 is the flat background
data = data / np.max(np.abs(data), axis=0) # dead units will be nan, not plotted
# plt.plot(np.max(data, axis=0))
# plt.imshow(data)
# plt.hist(data)
plt.plot(range(19), data)
plt.show()
def plot_murata_responses(n_layers):
with open('murata-' + str(n_layers) + '.pkl') as f:
data = cPickle.load(f)
if len(data.shape) == 4:
data = data[:,:,40,40]
print(data.shape)
# data = data - data[18,:] #18 is the flat background
data = data / np.max(np.abs(data), axis=0) # dead units will be nan, not plotted
# plt.plot(np.max(data, axis=0))
# plt.imshow(data)
# plt.hist(data)
plt.plot(data)
plt.show()
def sketch_perspectives(n_plot=100, offset_radius=0.):
np.random.seed(1)
sketch_points = np.array(
[[0., 0., 0., 0., 0., 0.],
[-.05, -.05, -.03, .03, .05, .05],
[.05, .03, 0, 0, .03, .05]]
)
with open('../../grasp-conv/data/relative/neuron-points.pkl', 'rb') as f:
neuron_points, neuron_angles = cPickle.load(f)
offsets = get_random_points(n_plot, offset_radius, surface=False)
from mpl_toolkits.mplot3d import axes3d, Axes3D
fig = plt.figure()
ax = fig.add_subplot(1,1,1,projection='3d')
for point, angle, offset in zip(neuron_points.T[:n_plot], neuron_angles.T[:n_plot], offsets.T):
r = get_rotation_matrix(point, angle)
r = np.eye(3)
sp = np.dot(r, sketch_points) + point[:,np.newaxis] + offset[:,np.newaxis]
ax.plot(sp[0], sp[1], sp[2], 'k')
plt.axis('off')
plt.savefig('perspective-sketch.pdf')
plt.show()
if __name__ == '__main__':
# plot_correct_point_scatter()
# plot_predictions()
# plot_points_with_correlations()
# depth = katsuyama_depth(200, -1.5, .8)
# depths = katsuyama_depths()
# for i in range(depths.shape[0]):
# plt.imshow(depths[i,:,:])
# print(depths[i,0,:])
# plt.show()
# layers = [2,4,6,9,12]
# for l in layers:
# print('running ' + str(l) + ' layers')
# # save_katsutama_responses('p-model-architecture-big.json', 'p-model-weights-big-9.h5', l)
# save_murata_respones('p-model-architecture-big.json', 'p-model-weights-big-9.h5', l)
# plot_katsuyama_responses(12)
plot_murata_responses(4)
# sketch_perspectives(n_plot=300, offset_radius=.15)
# sketch_perspectives(n_plot=1, offset_radius=.0)
| {
"repo_name": "bptripp/grasp-convnet",
"path": "py/perspective_analysis.py",
"copies": "1",
"size": "9936",
"license": "mit",
"hash": -8287427461598452000,
"line_mean": 30.8461538462,
"line_max": 100,
"alpha_frac": 0.5932971014,
"autogenerated": false,
"ratio": 2.913782991202346,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8967109348254264,
"avg_score": 0.007994148869616347,
"num_lines": 312
} |
__author__ = 'bptripp'
from os.path import join
import matplotlib.pyplot as plt
import cPickle
import numpy as np
import scipy
from data import load_all_params
# objects, gripper_pos, gripper_orient, labels = load_all_params('../../grasp-conv/data/output_data.csv')
# f = file('../data/metrics-objects.pkl', 'rb')
# oi, oq, of = cPickle.load(f) # intersections, qualities, files
# f.close()
# f = file('../data/metrics-support.pkl', 'rb')
# si, sq, sf = cPickle.load(f)
# f.close()
def count_cases(correlates, labels):
correlates = correlates.astype(int)
cases = np.zeros((np.max(correlates)+1,2), dtype=int)
for c, l in zip(correlates, labels):
cases[c,l] += 1
return cases
def get_collisions(oi, si):
oi = np.array(oi)
si = np.array(si)
# collision if any si < oi and si is not None
oi = np.where(oi == np.array(None), 900, oi)
si = np.where(si == np.array(None), 1000, si)
return np.sum(si < oi, axis=1) > 0
def check_objects_centred():
"""
The hand is supposed to be aimed at a point on the object, so central
pixel(s) should be on object, otherwise probably a bug (e.g. something
wrong with how mesh imported into V-REP).
"""
image_dir = '../../grasp-conv/data/obj_depths/'
im_width = 80
camera_offset=.45
near_clip=.25
far_clip=.8
from os import listdir
from os.path import isfile, join
from heuristic import finger_path_template
import scipy
finger_path = finger_path_template(45.*np.pi/180., im_width, camera_offset)
bad = []
background_threshold = 254
for f in listdir(image_dir):
image_filename = join(image_dir, f)
if isfile(image_filename) and f.endswith('.png'):
image = scipy.misc.imread(image_filename)
if np.min(image[39:41,39:41]) >= background_threshold:
bad.append(f)
print(f)
print(len(bad))
def regions_at_intersections(distance, intersections,
axis=0, directions=[-1,-1,1], length=5,
spans=[[32,38],[42,48],[37,43]]):
"""
:param distance: 2D distance map
:param intersections: pixel coords of finger-surface intersections
"""
regions = []
for i in range(len(intersections)):
direction = directions[i]
span = spans[i]
if axis==0:
d = distance
else:
d = distance.T
if direction < 0:
d = d[::-1,:]
if intersections[i] is None:
region = np.zeros((length,span[1]-span[0]))
else:
region = d[intersections[i]:intersections[i]+length,span[0]:span[1]]
regions.append(region)
return regions
#TODO: watch for outliers due to numerical sensitivity at sharp edges
def surface_slope(distance_map, threshold):
"""
Fits a plane to given points, ignoring values greater than a threshold distance
(meant to be the background).
"""
x = np.arange(0, distance_map.shape[1])
y = np.arange(0, distance_map.shape[0])
X, Y = np.meshgrid(x, y)
features = np.vstack((X.ravel(), Y.ravel(), np.ones_like(Y).ravel())).T
distances = distance_map.ravel()
include = distances <= threshold
if np.isnan(np.std(distances[include])):
return [0,0,np.mean(distances[include])]
else:
x, residuals, rank, s = np.linalg.lstsq(features[include,:], distances[include])
return x
def check_region_example():
camera_offset=.45
far_clip=.8
import scipy
image = scipy.misc.imread('../../grasp-conv/data/obj_depths/1_Coffeecup_final-03-Mar-2016-18-50-40-1.png')
rescaled_distance = image / 255.0
distance = rescaled_distance*(far_clip-camera_offset)+camera_offset
intersections = [38,36,21]
regions = regions_at_intersections(distance, intersections)
print(np.array(regions))
for region in regions:
print(surface_slope(region, far_clip-.005))
plt.imshow(distance)
plt.show()
#TODO: test
def angle_from_vertical(gripper_orient):
from depthmap import rot_matrix
R = rot_matrix(gripper_orient[0], gripper_orient[1], gripper_orient[2])
camera_vector = np.dot(R, np.array([0,0,1]))
return np.arccos(-camera_vector[2])
def object_area(distance, threshold):
return(np.sum(distance < threshold) / float(distance.size))
def object_centre(distance, threshold):
object = distance < threshold
x = np.arange(0, distance.shape[1])
y = np.arange(0, distance.shape[0])
X, Y = np.meshgrid(x, y)
return np.mean(X[object]), np.mean(Y[object])
def check_correlates():
data_file = '../../grasp-conv/data/output_data.csv'
objects, gripper_pos, gripper_orient, labels, power_pinch = load_all_params(data_file, return_power_pinch=True)
seq_nums = np.arange(len(objects)) % 1000
camera_offset=.45
far_clip=.8
threshold = far_clip - .005
for i in range(5):
image_filename = join('../../grasp-conv/data/obj_depths', objects[i][:-4] + '-' + str(seq_nums[i]) + '.png')
image = scipy.misc.imread(image_filename)
rescaled_distance = image / 255.0
distance = rescaled_distance*(far_clip-camera_offset)+camera_offset
print('angle: ' + str(angle_from_vertical(gripper_orient[i])))
print('area: ' + str(object_area(distance, threshold)))
print('centre: ' + str(object_centre(distance, threshold)))
plt.imshow(distance)
plt.show()
def get_correlates():
"""
Create a CSV file with a bunch of measures that may be correlates of grasp success.
"""
from heuristic import finger_path_template, calculate_grip_metrics
data_file = '../../grasp-conv/data/output_data.csv'
objects, gripper_pos, gripper_orient, labels, power_pinch = load_all_params(data_file, return_power_pinch=True)
seq_nums = np.arange(len(objects)) % 1000
labels = np.array(labels)
power_pinch = np.array(power_pinch)
camera_offset=.45
far_clip=.8
fov = 45.*np.pi/180.
im_width=80
finger_path = finger_path_template(fov, im_width, camera_offset)
background_threshold = far_clip - .005
result = []
for i in range(len(labels)):
data = [labels[i], power_pinch[i]]
image_filename = join('../../grasp-conv/data/obj_depths', objects[i][:-4] + '-' + str(seq_nums[i]) + '.png')
distance_image = scipy.misc.imread(image_filename)
rescaled_distance = distance_image / 255.0
distance = rescaled_distance*(far_clip-camera_offset)+camera_offset
intersections, qualities = calculate_grip_metrics(distance, finger_path)
regions = regions_at_intersections(distance, intersections)
for region in regions:
slope = surface_slope(region, background_threshold)
data.extend(slope[:2])
image_filename = join('../../grasp-conv/data/obj_overlap', objects[i][:-4] + '-' + str(seq_nums[i]) + '-overlap.png')
overlap_image = scipy.misc.imread(image_filename)
regions = regions_at_intersections(overlap_image, intersections, length=3)
for region in regions:
data.append(np.sum(region > 0) / float(region.size))
data.append(angle_from_vertical(gripper_orient[i]))
data.append(object_area(distance, background_threshold))
data.extend(object_centre(distance, background_threshold))
# intersections and quality metrics
intersections = np.where(intersections == np.array(None), im_width, intersections).astype(float)
data.extend(intersections)
data.extend(qualities)
# symmetry
rel_int = intersections / (im_width/2.)
data.append((rel_int[0]-rel_int[2])**2)
data.append((rel_int[1]-rel_int[2])**2)
# intersections with support box
image_filename = join('../../grasp-conv/data/support_depths', objects[i][:-4] + '-' + str(seq_nums[i]) + '.png')
distance_image = scipy.misc.imread(image_filename)
rescaled_distance = distance_image / 255.0
distance = rescaled_distance*(far_clip-camera_offset)+camera_offset
support_intersections, support_qualities = calculate_grip_metrics(distance, finger_path)
support_intersections = np.where(support_intersections == np.array(None), im_width, support_intersections).astype(float)
data.extend(support_intersections)
result.append(data)
# fig = plt.figure(figsize=(5,10))
# fig.add_subplot(2,1,1)
# plt.hist(power_pinch[labels<.5], range=(0, .20), bins=100)
# fig.add_subplot(2,1,2)
# plt.hist(power_pinch[labels>.5], range=(0, .20), bins=100)
# plt.show()
return np.array(result)
if __name__ == '__main__':
# check_objects_centred()
# save_correlates()
# weights = surface_slope(np.random.rand(4,6))
# print(weights)
# check_region_example()
#TODO: slopes and fractions of regions within finger path
# import scipy
# from os.path import join
# image_dir = '../../grasp-conv/data/obj_overlap/'
# image_file = '1_Coffeecup_final-03-Mar-2016-18-50-40-1-overlap.png'
# image = scipy.misc.imread(join(image_dir, image_file))
#
# intersections = [38,36,21]
# regions = regions_at_intersections(image, intersections, length=3)
# regions = np.array(regions)
# for region in regions:
# print(region)
# print(np.sum(region > 0) / float(region.size))
#
# plt.imshow(image)
# plt.show()
# check_correlates()
correlates = get_correlates()
import csv
with open('correlates.csv', 'wb') as csvfile:
cw = csv.writer(csvfile, delimiter=',')
for c in correlates:
cw.writerow(c)
| {
"repo_name": "bptripp/grasp-convnet",
"path": "py/analysis.py",
"copies": "1",
"size": "9741",
"license": "mit",
"hash": -4711622697899618000,
"line_mean": 31.6879194631,
"line_max": 128,
"alpha_frac": 0.6271430038,
"autogenerated": false,
"ratio": 3.318909710391823,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.44460527141918227,
"avg_score": null,
"num_lines": null
} |
__author__ = 'bptripp'
from os.path import join
import numpy as np
import matplotlib
matplotlib.rcParams['xtick.labelsize'] = 14
matplotlib.rcParams['ytick.labelsize'] = 14
import matplotlib.pyplot as plt
from cnn_stimuli import get_image_file_list
from alexnet import preprocess, load_net, load_vgg
# load IT neuron data from Kovacs figure 8 ...
kovacs = np.zeros((8,4))
NO = np.loadtxt(open('../data/NO.csv', 'rb'), delimiter=',')
kovacs[:,0] = NO[:,1]
MV20 = np.loadtxt(open('../data/MV20.csv', 'rb'), delimiter=',')
kovacs[:,1] = MV20[:,1]
MV50 = np.loadtxt(open('../data/MV50.csv', 'rb'), delimiter=',')
kovacs[:,2] = MV50[:,1]
MV90 = np.loadtxt(open('../data/MV90.csv', 'rb'), delimiter=',')
kovacs[:,3] = MV90[:,1]
def average_over_reps(responses, reps):
n_occ = responses.shape[0]/reps
averages = np.zeros((n_occ, responses.shape[1]))
for i in range(n_occ):
averages[i,:] = np.mean(responses[i*reps:(i+1)*reps,:], axis=0)
return averages
def plot(data, plot_colour):
assert data.shape[1] == 4
plt.figure(figsize=(3.5,3.5))
# max = data[0,0]
shape_index = range(1,data.shape[0]+1)
plt.plot(shape_index, data[:,0], plot_colour+'d-', label='NO')
plt.plot(shape_index, data[:,1], plot_colour+'o--', label='20%')
plt.plot(shape_index, data[:,2], plot_colour+'^-.', label='50%')
plt.plot(shape_index, data[:,3], plot_colour+'s:', label='90%')
plt.legend(loc='upper right', shadow=False, frameon=False)
plt.xlabel('Shape rank', fontsize=16)
plt.ylabel('Mean Response', fontsize=16)
plt.tight_layout()
def get_mean_responses(use_vgg, remove_level):
if use_vgg:
model = load_vgg(weights_path='../weights/vgg16_weights.h5', remove_level=remove_level)
else:
model = load_net(weights_path='../weights/alexnet_weights.h5', remove_level=remove_level)
reps = 10
out = []
shapes = ['circle', 'square', 'star', 'triangle', 'strange', 'h', 'arrow', 'stop']
for shape in shapes:
image_files = get_image_file_list(join(base_directory, shape), 'png', with_path=True)
im = preprocess(image_files, use_vgg=use_vgg)
out.append(average_over_reps(model.predict(im), reps))
out = np.array(out)
print(out.shape)
unoccluded_responses = out[:,0,:]
print(unoccluded_responses.shape)
var = np.var(unoccluded_responses, axis=0)
n = 500
ind = (-var).argsort()[:n]
# ind = range(n)
most_selective = out[:,:,ind]
most_sorted = np.zeros_like(most_selective)
for i in range(n):
order = np.argsort(most_selective[:,0,i])[::-1]
most_sorted[:,:,i] = most_selective[order,:,i]
# out: shape, occlusion, neuron
means = np.mean(most_sorted, axis=2)
return means[:,:4]-means[:,4,None]
use_vgg = True
if use_vgg:
plot_colour = 'g'
else:
plot_colour = 'b'
# occlusion_type = 'black'
# occlusion_type = 'red'
occlusion_type = 'moving'
base_directory = './images/occlusions-' + occlusion_type
# # plot figure like Kovacs ...
# remove_level = 1
# means = get_mean_responses(use_vgg, remove_level)
# plot(means, plot_colour)
# if use_vgg:
# plt.savefig('../figures/occlusions-' + occlusion_type + '-vgg-' + str(remove_level) + '.eps')
# else:
# plt.savefig('../figures/occlusions-' + occlusion_type + '-alexnet-' + str(remove_level) + '.eps')
# plt.show()
# # replot Kovacs data ...
# plot(kovacs, 'k')
# plt.savefig('../figures/occlusions-kovacs.eps')
# plt.show()
# plot functions of occlusion level ...
visibility = [100, 80, 50, 10]
plt.figure(figsize=(3.5,3.5))
kovacs_relative = kovacs[0,:] - kovacs[-1,:]
plt.plot(visibility, kovacs_relative/kovacs_relative[0], 'k', label='IT')
remove_levels = [0, 1, 2]
labels = ['last layer', '2nd last', '3rd last']
line_formats = ['-', '--', '-.']
for i in range(3):
means = get_mean_responses(use_vgg, remove_levels[i])
relative = means[0,:] - means[-1,:]
plt.plot(visibility, relative/relative[0], plot_colour+line_formats[i], label=labels[i])
plt.legend(loc='upper left', shadow=False, frameon=False)
plt.xlabel('Percent Visible', fontsize=16)
plt.ylabel('Mean Normalized Response', fontsize=16)
plt.xticks([20, 40, 60, 80, 100])
plt.ylim([-.1, 1.1])
plt.tight_layout()
network_name = 'vgg' if use_vgg else 'alexnet'
plt.savefig('../figures/occlusions-sigmoid-' + occlusion_type + '-' + network_name + '.eps')
plt.show()
| {
"repo_name": "bptripp/it-cnn",
"path": "tuning/occlusion.py",
"copies": "1",
"size": "4383",
"license": "mit",
"hash": 8586947636810286000,
"line_mean": 32.4580152672,
"line_max": 103,
"alpha_frac": 0.6354095368,
"autogenerated": false,
"ratio": 2.851659076122316,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.3987068612922316,
"avg_score": null,
"num_lines": null
} |
__author__ = 'bptripp'
import argparse
import logging
from os import listdir, rename
from os.path import isfile, join, isdir, basename, split
import cPickle as pickle
import numpy as np
import matplotlib.pyplot as plt
import time
from alexnet import preprocess, load_net
from auction import auction
"""
TODO:
- DONE load minibatch images
- DONE run network to get existing tuning
- DONE generate orientation tuning samples
- DONE choose Bertsekas integer resolution
- DONE dicard all but ~200 output units
- DONE normalize and use Bertsekas to pair up with empirical model
- DONE scale empirical responses and make labels
- DONE generator
- LATER optionally resample orientation tuning curves each minibatch to reduce sampling bias (although there are many samples)
- LATER recharacterize all tuning
- DONE load existing network & strip last layer
- DONE code to generate and save minibatch list
- DONE organize files better to reduce looping to find orientations
"""
def make_ideal_tuning_curves(angles, n):
# from Salman's paper
curves = np.zeros((len(angles), n))
prefs = 360.*np.random.rand(n)
i = 0
widths = np.zeros(n)
while i < n:
width = 30. + 15. * np.random.randn()
if width > 1:
widths[i] = width
i = i + 1
for i in range(n):
da = angles - prefs[i]
da[da > 180] = da[da > 180] - 360
da[da < -180] = da[da < -180] + 360
curves[:,i] = np.exp(-(da)**2 / 2 / widths[i]**2)
# plt.plot(angles, curves)
# plt.title('Empirical')
# plt.ylim([0,1])
# plt.show()
return curves
def find_stimuli(image_path, extension):
stimuli = set()
for d in listdir(image_path):
if isdir(join(image_path, d)):
for f in listdir(join(image_path, d)):
if isfile(join(image_path, d, f)) and f.endswith(extension):
parts = f.split('-')
stim_name = parts[0] + '-' + parts[1]
stimuli.add(join(image_path, d, stim_name))
return list(stimuli)
def get_images(stimulus, extension):
return preprocess(get_image_paths(stimulus, extension))
def get_image_paths(stimulus, extension):
directory, partial_name = split(stimulus)
return [join(directory, f) for f in listdir(directory) if f.startswith(partial_name + '-') and f.endswith(extension)]
def get_similarities(actual_curves, ideal_curves):
actual_normalized = normalize_curves(actual_curves)
ideal_normalized = normalize_curves(ideal_curves)
return np.dot(actual_normalized.T, ideal_normalized)
def normalize_curves(tuning_curves):
#one tuning curve per column
nm = np.linalg.norm(tuning_curves, axis=0, ord=2) + 1e-6
return tuning_curves / nm[None,:]
def get_XY(model, stimulus, baseline_mean):
images = get_images(stimulus, extension)
actual_curves = model.predict(images)
logging.info(stimulus)
n = 200
ideal_curves = make_ideal_tuning_curves(angles, n)
assignments = get_assignments(actual_curves[:,:n], ideal_curves)
#similarities = get_similarities(actual_curves[:,:n], ideal_curves)
#A = ((1+similarities)*50).astype(int)
#assignments, prices = auction(A)
logging.debug('ideal curves shape: ' + str(ideal_curves.shape))
#logging.debug('similarities shape: ' + str(similarities.shape))
logging.debug('assignments shape: ' + str(assignments.shape))
target_curves = get_targets(actual_curves, ideal_curves, assignments, baseline_mean)
logging.debug('images shape: ' + str(images.shape))
logging.debug('target curves shape: ' + str(target_curves.shape))
return images, target_curves
def get_cost(model, stimulus, baseline_mean):
images = get_images(stimulus, extension)
actual_curves = model.predict(images)
n = 200
ideal_curves = make_ideal_tuning_curves(angles, n)
assignments = get_assignments(actual_curves[:,:n], ideal_curves)
target_curves = get_targets(actual_curves, ideal_curves, assignments, baseline_mean)
return np.mean((actual_curves - target_curves)**2)
def get_assignments(actual_curves, ideal_curves):
similarities = get_similarities(actual_curves, ideal_curves)
A = ((1+similarities)*50).astype(int)
assignments, prices = auction(A)
return assignments
def get_targets(actual_curves, ideal_curves, assignments, baseline_mean):
n = ideal_curves.shape[1]
target_curves = actual_curves.copy()
for i in range(n):
target_curves[:,i] = ideal_curves[:,int(assignments[i])]
scale_factor = np.abs(np.mean(actual_curves[:,i]) / np.mean(target_curves[:,i]))
target_curves[:,i] = target_curves[:,i] * scale_factor
if baseline_mean is not None:
#maintain the mean so targets don't sneak down to zero
target_mean = np.mean(target_curves[:,:n])
if target_mean > 0:
target_curves[:,:n] = target_curves[:,:n] * baseline_mean / target_mean
return target_curves
def fix_file_names(image_path):
for file_name in listdir(image_path):
if isdir(join(image_path, file_name)):
new_name = file_name.replace('-', '_')
if not new_name == file_name:
print('renaming ' + join(image_path, file_name) + ' to ' + join(image_path, new_name))
rename(join(image_path, file_name), join(image_path, new_name))
for image_file_name in listdir(join(image_path, new_name)):
image_new_name = image_file_name.replace(file_name, new_name)
print('renaming ' + join(image_path, new_name, image_file_name)
+ ' to ' + join(image_path, new_name, image_new_name))
rename(join(image_path, new_name, image_file_name),
join(image_path, new_name, image_new_name))
if __name__ == '__main__':
logging.basicConfig(filename='orientation.log', level=logging.DEBUG)
parser = argparse.ArgumentParser()
parser.add_argument('train_image_path', help='path to stimulus images for training')
parser.add_argument('valid_image_path', help='path to stimulus images for validation')
train_image_path = parser.parse_args().train_image_path
valid_image_path = parser.parse_args().valid_image_path
fix_file_names(valid_image_path)
fix_file_names(train_image_path)
extension = '.png'
train_stimuli = find_stimuli(train_image_path, extension)
valid_stimuli = find_stimuli(valid_image_path, extension)
print(len(listdir(train_image_path)))
print(len(listdir(valid_image_path)))
print('Processing ' + str(len(train_stimuli)) + ' training inputs from ' + train_image_path)
print('Processing ' + str(len(valid_stimuli)) + ' validation inputs from ' + valid_image_path)
# for fn in listdir(train_image_path):
# if isdir(join(train_image_path, fn)):
# l = len(listdir(join(train_image_path, fn)))
# print(str(l) + ' in ' + fn)
angles = range(0, 361, 10)
model = load_net()
# plt.figure(figsize=(8,8))
#
# for i in range(8):
# for j in range(8):
# ind = 8*i+j
# plt.subplot(8,8,ind+1)
# plt.plot(actual_curves[:,ind])
# # plt.plot(ideal_curves[:,assignments[ind]])
# plt.plot(target_curves[:,ind])
#
# plt.show()
# find baseline mean rate with some random stimuli
baseline_means = []
baseline_inds = np.random.randint(len(valid_stimuli), size=10)
for ind in baseline_inds:
print('baseline from ' + valid_stimuli[ind])
images = get_images(valid_stimuli[ind], extension)
baseline_means.append(np.mean(model.predict(images)))
baseline_mean = np.mean(baseline_means)
def generate_training():
while 1:
ind = np.random.randint(0, len(train_stimuli))
X, Y = get_XY(model, train_stimuli[ind], baseline_mean)
yield X, Y
def generate_validation():
while 1:
ind = np.random.randint(0, len(valid_stimuli))
X, Y = get_XY(model, valid_stimuli[ind], None)
yield X, Y
val_cost = []
for i in range(50):
h = model.fit_generator(generate_training(),
samples_per_epoch=len(train_stimuli)*len(angles), nb_epoch=1)
#validation_data=generate_validation(), nb_val_samples=len(valid_stimuli)*len(angles))
val_cost_i = []
for vs in valid_stimuli:
val_cost_i.append(get_cost(model, vs, baseline_mean))
val_cost.append(np.mean(val_cost_i))
print('validation cost: ' + str(np.mean(val_cost_i)))
with open('orientation_history.pkl', 'wb') as f:
pickle.dump(val_cost, f)
model.save_weights('orientation_weights' + str(i) + '.h5', overwrite=True)
#f = open('orientation_history.pkl', 'wb')
#pickle.dump(h.history, f)
#f.close()
| {
"repo_name": "bptripp/it-cnn",
"path": "orientation.py",
"copies": "1",
"size": "8926",
"license": "mit",
"hash": -6839530519317261000,
"line_mean": 34.2806324111,
"line_max": 126,
"alpha_frac": 0.6342146538,
"autogenerated": false,
"ratio": 3.452998065764023,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9549400756721746,
"avg_score": 0.00756239256845513,
"num_lines": 253
} |
__author__ = 'bptripp'
import argparse
import numpy as np
import cPickle as pickle
import matplotlib.pyplot as plt
from alexnet import preprocess, load_net
from orientation import find_stimuli, get_images
parser = argparse.ArgumentParser()
parser.add_argument('action', help='either save (evaluate and save tuning curves) or plot (plot examples)')
parser.add_argument('valid_image_path', help='path to stimulus images for validation')
valid_image_path = parser.parse_args().valid_image_path
action = parser.parse_args().action
curves_file = 'orientation_curves.pkl'
n = 200
if action == 'save':
model = load_net()
model.load_weights('orientation_weights.h5')
extension = '.png'
valid_stimuli = find_stimuli(valid_image_path, extension)
curves = []
for stimulus in valid_stimuli:
print(stimulus)
images = get_images(stimulus, extension)
curves.append(model.predict(images)[:,:n])
curves = np.array(curves, dtype=np.float16)
print(curves.shape)
f = open(curves_file, 'wb')
pickle.dump((valid_stimuli, curves), f)
f.close()
if action == 'plot':
f = open(curves_file, 'rb')
valid_stimuli, curves = pickle.load(f)
f.close()
plt.figure(figsize=(12,12))
for i in range(8):
for j in range(8):
ind = 8*i+j
plt.subplot(8,8,ind+1)
plt.plot(curves[0,:,ind])
plt.show()
| {
"repo_name": "bptripp/it-cnn",
"path": "orientation_analysis.py",
"copies": "1",
"size": "1404",
"license": "mit",
"hash": -7949491637300808000,
"line_mean": 26.5294117647,
"line_max": 107,
"alpha_frac": 0.6602564103,
"autogenerated": false,
"ratio": 3.334916864608076,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.44951732749080764,
"avg_score": null,
"num_lines": null
} |
__author__ = 'bptripp'
import cPickle as pickle
from scipy.optimize import curve_fit
import numpy as np
import matplotlib
matplotlib.rcParams['xtick.labelsize'] = 16
matplotlib.rcParams['ytick.labelsize'] = 16
import matplotlib.pyplot as plt
from cnn_stimuli import get_image_file_list
from alexnet import preprocess, load_net, load_vgg
from orientation import smooth
offsets = np.linspace(-75, 75, 150/5+1, dtype=int)
def get_centre_of_mass(y):
"""
Centre of mass of a tuning function as in Op De Beeck et al. (2000), including
only points >50% of peak.
"""
ind = y > .5*np.max(y)
masked = np.zeros(y.shape)
masked[ind] = y[ind]
return np.sum(offsets*masked) / np.sum(masked)
def get_width(y):
"""
Width of a tuning function as in Op De Beeck et al. (2000); distance between where it falls
to 50% of peak on each side.
"""
max_ind = np.argmax(y)
below_threshold = y < .5*np.max(y)
# print(below_threshold)
# low_and_left = np.logical_and(range(len(y)) < max_ind, below_threshold)
# low_and_right = np.logical_and(range(len(y)) > max_ind, below_threshold)
#
# if max(low_and_left):
# low_ind = np.max(np.where(low_and_left))
# else:
# low_ind = 0
#
# if max(low_and_right):
# high_ind = np.min(np.where(low_and_right))
# else:
# high_ind = len(y)-1
for i in range(max_ind, -1, -1):
if below_threshold[i]:
break
if i == 0:
low_ind = i
else:
low_ind = i + 1
for i in range(max_ind, len(y)):
if below_threshold[i]:
break
if i == len(y) - 1:
high_ind = i
else:
high_ind = i - 1
# print(y)
# print('threshold: ' + str(.5*np.max(y)))
# print(max_ind)
# print(low_ind)
# print(high_ind)
# print('*******')
#
return offsets[high_ind] - offsets[low_ind]
if False:
# plot selectivity vs. position tolerance
model = load_net()
image_files = get_image_file_list('./images/positions/banana', 'png', with_path=True)
im = preprocess(image_files)
out = model.predict(im)
with open('activity-fraction.pkl', 'rb') as file:
(ind, selectivity) = pickle.load(file)
# n = 674
n = len(ind)
print(n)
object_responses = out[:,ind]
plt.plot(offsets, object_responses)
plt.show()
# maxima = np.max(out, axis=0)
# ind = (-maxima).argsort()[:n]
# smoothed = smooth(object_responses, ind)
def get_sd(x, y):
x = np.array(x, dtype=float)
mean = sum(x*y)/n
sigma = (sum(y*(x-mean)**2)/n)**.5
return sigma
widths = np.zeros(n)
good_selectivity = []
good_widths = []
for i in range(n):
widths[i] = get_sd(offsets, object_responses[:,i])
if np.mean(object_responses[:,i]) > .001:
good_selectivity.append(selectivity[i])
good_widths.append(widths[i])
# if widths[i] < 1:
# print(object_responses[:,i])
with open('selectivity-vs-pos-tolerance.pkl', 'wb') as file:
pickle.dump((good_selectivity, good_widths), file)
print(np.corrcoef(good_selectivity, good_widths))
plt.scatter(good_selectivity, good_widths)
plt.show()
if True:
# alexnet 0: mean width: 146.208333333 std centres: 3.49089969478
# alexnet 1: mean width: 138.875 std centres: 5.96841285709
# alexnet 2: mean width: 112.583333333 std centres: 23.4025005388
# vgg 0: mean width: 150.0 std centres: 1.12932654355
# vgg 1: mean width: 150.0 std centres: 1.422815326
# vgg 2: mean width: 141.916666667 std centres: 11.2126510706
data = np.loadtxt(open("../data/op-de-beeck-6.csv","rb"),delimiter=",")
x = data[:,0]
it_std_rf_centre = np.std(x)
it_mean_rf_size = 10.3 # from Op De Beeck
# # strongest 30 responses ...
# alexnet_std_rf_centre = np.array([23.4025005388, 5.96841285709, 3.49089969478])
# alexnet_mean_rf_size = np.array([112.583333333, 138.875, 146.208333333])
# vgg_std_rf_centre = np.array([11.2126510706, 1.422815326, 1.12932654355])
# vgg_mean_rf_size = np.array([141.916666667, 150.0, 150.0])
# first 30 strong responses ...
alexnet_std_rf_centre = np.array([30.2666393886, 14.4771892017, 5.46262378919])
alexnet_mean_rf_size = np.array([62.5833333333, 108.625, 140.333333333])
vgg_std_rf_centre = np.array([22.2973512678, 3.0048651618, 2.26856624582])
vgg_mean_rf_size = np.array([97.5, 147.916666667, 149.625])
layers = [-2, -1, 0]
plt.figure(figsize=(5,3.5))
plt.plot(layers, alexnet_std_rf_centre / alexnet_mean_rf_size, 'o-')
plt.plot(layers, vgg_std_rf_centre / vgg_mean_rf_size, 's-')
plt.plot(layers, it_std_rf_centre/it_mean_rf_size*np.array([1, 1, 1]), 'k--')
plt.xlabel('Distance from output (layers)', fontsize=16)
plt.ylabel('STD of centers / mean width', fontsize=16)
plt.xticks([-2,-1,0])
plt.tight_layout()
plt.savefig('../figures/position-variability.eps')
plt.show()
if False:
# plot tuning curve examples
remove_level = 0
# model = load_net(weights_path='../weights/alexnet_weights.h5', remove_level=remove_level)
# use_vgg = False
model = load_vgg(weights_path='../weights/vgg16_weights.h5', remove_level=remove_level)
use_vgg = True
out = []
image_files = get_image_file_list('./images/positions/staple', 'png', with_path=True)
im = preprocess(image_files, use_vgg=use_vgg)
out.append(model.predict(im))
image_files = get_image_file_list('./images/positions/shoe', 'png', with_path=True)
im = preprocess(image_files, use_vgg=use_vgg)
out.append(model.predict(im))
image_files = get_image_file_list('./images/positions/corolla', 'png', with_path=True)
im = preprocess(image_files, use_vgg=use_vgg)
out.append(model.predict(im))
image_files = get_image_file_list('./images/positions/banana', 'png', with_path=True)
im = preprocess(image_files, use_vgg=use_vgg)
out.append(model.predict(im))
out = np.array(out)
# print(out.shape)
# plot example tuning curves
n = 30
labels = ('staple', 'shoe', 'car', 'banana')
plt.figure(figsize=(6,6))
centres = []
widths = []
for i in range(4):
object_responses = np.squeeze(out[i,:,:])
# print(object_responses.shape)
maxima = np.max(object_responses, axis=0)
# ind = (-maxima).argsort()[:n]
print('using first large n')
ind = []
j = 0
while len(ind) < n:
if maxima[j] > 2:
ind.append(j)
j = j + 1
smoothed = smooth(object_responses, ind)
for j in range(smoothed.shape[1]):
centres.append(get_centre_of_mass(smoothed[:,j]))
widths.append(get_width(smoothed[:,j]))
# plt.plot(offsets, object_responses[:,ind])
plt.subplot(2,2,i+1)
if i >= 2:
plt.xlabel('Offset (pixels)', fontsize=16)
if i == 0 | i == 3:
plt.ylabel('Response', fontsize=16)
plt.title(labels[i], fontsize=16)
plt.plot(offsets, smoothed)
plt.xticks([-75,-25,25,75])
plt.tight_layout()
print(centres)
print(widths)
print('mean width: ' + str(np.mean(widths)) + ' std centres: ' + str(np.std(centres)))
net = 'vgg16' if use_vgg else 'alexnet'
plt.savefig('../figures/position-tuning-' + net + '-' + str(remove_level) + '.eps')
plt.show()
def correlations(out):
cc = np.corrcoef(out.T)
result = []
for i in range(cc.shape[0]):
for j in range(i+1,cc.shape[1]):
result.append(cc[i][j])
return result
def invariant(out):
return np.mean(correlations(out)) > .5
def clear_preference(out):
# one size is clearly preferred in that it elicits a stronger response for each shape
max_ind = np.argmax(out, axis=1)
votes = np.zeros((5))
for m in max_ind:
votes[m] = votes[m] + 1
return np.max(votes) >= 5
# return np.max(np.abs(np.diff(max_ind))) == 0
if False:
# plot Schwartz et al. (1983) example
U = np.loadtxt(open('../data/U.csv', 'rb'), delimiter=',')
L = np.loadtxt(open('../data/L.csv', 'rb'), delimiter=',')
C = np.loadtxt(open('../data/C.csv', 'rb'), delimiter=',')
I = np.loadtxt(open('../data/I.csv', 'rb'), delimiter=',')
F = np.loadtxt(open('../data/F.csv', 'rb'), delimiter=',')
o = np.zeros((6,5))
o[:,0] = U[:,1]
o[:,1] = L[:,1]
o[:,2] = C[:,1]
o[:,3] = I[:,1]
o[:,4] = F[:,1]
plt.figure(figsize=(4,3.5))
plt.plot(range(1,7), o)
plt.tight_layout()
plt.xlabel('Stimulus #', fontsize=18)
plt.ylabel('Response (spikes/s)', fontsize=18)
plt.tight_layout()
plt.savefig('../figures/position-schwartz-example.eps')
plt.show()
print('Schwartz correlation ' + str(np.mean(correlations(o))))
if False:
# plot mean correlations and fraction with clear preference
layers = [-2, -1, 0]
plt.figure(figsize=(4,3.5))
alexnet_correlations = [0.350468586188, 0.603050738337, 0.813774571373]
vgg_correlations = [0.578857429221, 0.8000155323, 0.928289856194]
schwartz_correlation = 0.791299618127
plt.plot(layers, alexnet_correlations)
plt.plot(layers, vgg_correlations)
plt.plot(layers, schwartz_correlation*np.array([1, 1, 1]), 'k--')
plt.xlabel('Distance from output (layers)', fontsize=16)
plt.ylabel('Mean correlation', fontsize=16)
plt.xticks([-2,-1,0])
plt.ylim([0, 1])
plt.tight_layout()
plt.savefig('../figures/position-correlations.eps')
plt.show()
plt.figure(figsize=(4,3.5))
alexnet_fractions = [0.21875, 0.125, 0.046875]
vgg_fractions = [0.078125, 0.109375, 0.0]
plt.plot(layers, alexnet_fractions)
plt.plot(layers, vgg_fractions)
plt.xlabel('Distance from output (layers)', fontsize=16)
plt.ylabel('Fraction with preference', fontsize=16)
plt.xticks([-2,-1,0])
plt.ylim([0, 1])
plt.tight_layout()
plt.savefig('../figures/position-preferences.eps')
plt.show()
if False:
use_vgg = True
remove_level = 0
if use_vgg:
model = load_vgg(weights_path='../weights/vgg16_weights.h5', remove_level=remove_level)
else:
model = load_net(weights_path='../weights/alexnet_weights.h5', remove_level=remove_level)
out = []
stimuli = ['f1', 'f2', 'f3', 'f4', 'f5', 'f6']
for stimulus in stimuli:
image_files = get_image_file_list('./images/positions/'+stimulus, 'png', with_path=True)
im = preprocess(image_files, use_vgg=use_vgg)
out.append(model.predict(im))
out = np.array(out)
print(out.shape)
# plot invariance with Schwartz stimuli
i = 0
c = 0
n_invariant = 0
n_clear = 0
mean_correlations = []
while c < 64:
plt.subplot(8,8,c+1)
o = out[:,:,i]
if np.max(o) > 1:
plt.plot(o)
yl = plt.gca().get_ylim()
if invariant(o):
n_invariant = n_invariant + 1
plt.text(4.3, yl[0] + (yl[1]-yl[0])*.8, 'c', fontsize=14)
if clear_preference(o):
n_clear = n_clear + 1
plt.text(.1, yl[0] + (yl[1]-yl[0])*.8, 'p', fontsize=14)
mean_correlations.append(np.mean(correlations(o)))
plt.xticks([])
plt.yticks([])
c = c + 1
i = i + 1
print(mean_correlations)
print('fraction with preference ' + str(float(n_clear)/64.))
print('mean correlation ' + str(np.nanmean(mean_correlations)))
plt.tight_layout()
network_name = 'vgg' if use_vgg else 'alexnet'
plt.savefig('../figures/position-invariance-schwartz-' + network_name + '-' + str(remove_level) + '.eps')
plt.show()
| {
"repo_name": "bptripp/it-cnn",
"path": "tuning/position.py",
"copies": "1",
"size": "11797",
"license": "mit",
"hash": -8436449798592760000,
"line_mean": 30.1266490765,
"line_max": 109,
"alpha_frac": 0.5937950326,
"autogenerated": false,
"ratio": 2.9745335350479074,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.40683285676479075,
"avg_score": null,
"num_lines": null
} |
__author__ = 'bptripp'
import cPickle
import csv
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D
from data import get_prob_label, get_points
from depthmap import rot_matrix, loadOBJ
def export_overlap_results():
with open('o-predict.pkl', 'rb') as f:
outputs, targets = cPickle.load(f)
print(outputs.shape)
print(targets.shape)
with open('o-predict.csv', 'wb') as f:
writer = csv.writer(f, delimiter=',')
for output, target in zip(outputs, targets):
writer.writerow([output[0], target[0]])
def plot_success_prob():
shape = '24_bowl-02-Mar-2016-07-03-29'
param_filename = '../data/params/' + shape + '.csv'
points, labels = get_points(param_filename)
# z = np.linspace(-4 * np.pi, 4 * np.pi, 300)
# x = np.cos(z)
# y = np.sin(z)
# z = [1, 2]
# x = [1, 2]
# y = [1, 2]
#
# fig = plt.figure()
# ax = fig.gca(projection='3d')
# ax.plot(x, y, z,
# color = 'Blue', # colour of the curve
# linewidth = 3, # thickness of the line
# )
fig = plt.figure()
ax = Axes3D(fig)
red = np.array([1.0,0.0,0.0])
green = np.array([0.0,1.0,0.0])
obj_filename = '../data/obj_files/' + shape + '.obj'
verts, faces = loadOBJ(obj_filename)
verts = np.array(verts)
minz = np.min(verts, axis=0)[2]
verts[:,2] = verts[:,2] + 0.2 - minz
show_flags = np.random.rand(verts.shape[0]) < .25
ax.scatter(verts[show_flags,0], verts[show_flags,1], verts[show_flags,2], c='b')
for i in range(1000):
point = points[i]
prob, confidence = get_prob_label(points, labels, point, sigma_p=1.5*.001, sigma_a=1.5*(4*np.pi/180))
goodness = prob * np.minimum(1, .5 + .15*confidence)
rm = rot_matrix(point[3], point[4], point[5])
pos = point[:3]
front = pos + np.dot(rm,[0,0,.15])
left = pos - np.dot(rm,[0.0,0.005,0])
right = pos + np.dot(rm,[0.0,0.01,0])
# if goodness > .85:
if prob > .9:
ax.plot([pos[0],front[0]], [pos[1],front[1]], [pos[2],front[2]],
color=(prob*green + (1-prob)*red),
linewidth=confidence)
ax.plot([left[0],right[0]], [left[1],right[1]], [left[2],right[2]],
color=(prob*green + (1-prob)*red),
linewidth=confidence)
plt.show()
if __name__ == '__main__':
# plot_success_prob()
export_overlap_results()
| {
"repo_name": "bptripp/grasp-convnet",
"path": "py/plots.py",
"copies": "1",
"size": "2538",
"license": "mit",
"hash": -2312333928488435700,
"line_mean": 30.725,
"line_max": 109,
"alpha_frac": 0.5413711584,
"autogenerated": false,
"ratio": 2.9205983889528193,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8926573113653251,
"avg_score": 0.007079286739913615,
"num_lines": 80
} |
__author__ = 'bptripp'
import csv
import time
import numpy as np
import matplotlib.pyplot as plt
from cnn_stimuli import get_image_file_list
from alexnet import preprocess, load_net, load_vgg
from scipy.signal import fftconvolve
def mean_corr(out):
cc = np.corrcoef(out.T)
n = cc.shape[0]
print('n: ' + str(n))
print(out.shape)
cc_list = []
for i in range(n):
for j in range(i+1,n):
cc_list.append(cc[i,j])
print(cc_list)
mean_cc = np.mean(cc_list)
print('mean corr: ' + str(mean_cc))
def smooth(out, ind, n=5):
l = out.shape[0]
wrapped = np.zeros((out.shape[0]*3, len(ind)))
wrapped[0:l,:] = out[:,ind]
wrapped[l:2*l,:] = out[:,ind]
wrapped[2*l:3*l,:] = out[:,ind]
filter = 1./n*np.ones(n)
# print('filter: ' + str(filter))
for i in range(wrapped.shape[1]):
wrapped[:,i] = fftconvolve(wrapped[:,i], filter, 'same')
return wrapped[l:2*l,:]
def plot_curves(out, n, kernel_len=5, angles=None, normalize=False):
print('plotting')
if angles is None:
angles = np.linspace(0, 360, 91)
maxima = np.max(out, axis=0)
# n = 10
# ind = (-maxima).argsort()[:n]
# print('using first n')
# ind = range(n)
print('using first large n')
ind = []
i = 0
while len(ind) < n:
if maxima[i] > 2:
ind.append(i)
i = i + 1
print(ind)
smoothed = smooth(out, ind, n=kernel_len)
# if smooth:
# smoothed = smooth(out, ind)
# else:
# smoothed = out[:,ind]
mean_corr(smoothed)
# print(len(angles))
# print(smoothed.shape)
if normalize:
smoothed = smoothed / np.max(smoothed, axis=0)
plt.plot(angles, smoothed)
plt.xlim([np.min(angles), np.max(angles)])
def freiwald_depths(out):
"""
From Freiwald & Tsao (2010) Science, supplementary material, page 6 ...
Head orientation tuning depth was computed using the mean
response to frontal faces (Rfrontal), and the mean response to full profile faces in the preferred
direction (Rprofile) as follows:
Tuning Depth = (Rfrontal - Rprofile) / (Rfrontal + Rprofile)
"""
assert(out.shape[0] == 25)
frontal = np.maximum(0, out[0,:])
profile = np.maximum(0, np.maximum(out[6,:], out[19,:]))
m = np.max(out, axis=0)
frontal = frontal[m >= 1]
profile = profile[m >= 1]
return (frontal - profile) / (frontal + profile + 1e-3)
def plot_freiwald_histograms():
fractions = []
fractions.append(np.loadtxt(open("../data/freiwald-4h-am.csv","rb"),delimiter=","))
fractions.append(np.loadtxt(open("../data/freiwald-4h-al.csv","rb"),delimiter=","))
fractions.append(np.loadtxt(open("../data/freiwald-4h-mlmf.csv","rb"),delimiter=","))
plt.figure(figsize=(3,2*3))
for i in range(3):
plt.subplot(3,1,i+1)
f = fractions[i]
hist_edges = np.linspace(-1, 1, len(f)+1)
# hist_edges = hist_edges[:-1]
print(f.shape)
print(hist_edges.shape)
plt.bar(hist_edges[:-1]+.02, f, width=hist_edges[1]-hist_edges[0]-.04, color=[.5,.5,.5])
plt.xlim([-1, 1])
plt.ylim([0, .55])
plt.ylabel('Fraction of cells')
plt.xlabel('Head orientation tuning depth')
plt.tight_layout()
plt.savefig('../figures/orientation-freiwald.eps')
plt.show()
def plot_logothetis_and_freiwald_tuning_data():
plt.figure(figsize=(9,2.5))
plt.subplot(1,3,1)
plot_csv_tuning_curve('../data/logothetis-a.csv')
plot_csv_tuning_curve('../data/logothetis-b.csv')
plot_csv_tuning_curve('../data/logothetis-c.csv')
plot_csv_tuning_curve('../data/logothetis-d.csv')
plot_csv_tuning_curve('../data/logothetis-e.csv')
plt.ylabel('Response')
plt.xlabel('Angle (degrees)')
plt.xlim([-180, 180])
plt.xticks([-180, -60, 60, 180])
plt.subplot(1,3,3)
plot_csv_tuning_curve('../data/freiwald-1.csv')
plot_csv_tuning_curve('../data/freiwald-2.csv')
plot_csv_tuning_curve('../data/freiwald-3.csv')
plot_csv_tuning_curve('../data/freiwald-4.csv')
plt.xlabel('Angle (degrees)')
plt.xlim([-180, 180])
plt.xticks([-180, -60, 60, 180])
plt.tight_layout()
plt.savefig('../figures/tuning-data.eps')
plt.show()
def plot_csv_tuning_curve(filename):
data = np.loadtxt(open(filename, 'rb'), delimiter=',')
ind = np.argsort(data[:,0])
plt.plot(data[ind,0], data[ind,1])
if __name__ == '__main__':
# model = load_vgg(weights_path='../weights/vgg16_weights.h5', remove_level=2)
# use_vgg = True
# model = load_net(weights_path='../weights/alexnet_weights.h5', remove_level=1)
# use_vgg = False
#
# plt.figure(figsize=(6,6))
# # image_files = get_image_file_list('./images/swiss-knife-rotations/', 'png', with_path=True)
# image_files = get_image_file_list('./images/staple-rotations/', 'png', with_path=True)
# im = preprocess(image_files, use_vgg=use_vgg)
# out = model.predict(im)
# # plt.subplot(2,2,1)
# plt.subplot2grid((5,2), (0,0), rowspan=2)
# plot_curves(out, 10)
# # plt.ylim([0,12])
# plt.ylabel('Response')
# image_files = get_image_file_list('./images/shoe-rotations/', 'png', with_path=True)
# im = preprocess(image_files, use_vgg=use_vgg)
# out = model.predict(im)
# # plt.subplot(2,2,2)
# plt.subplot2grid((5,2), (0,1), rowspan=2)
# plot_curves(out, 10)
# # plt.ylim([0,12])
# image_files = get_image_file_list('./images/corolla-rotations/', 'png', with_path=True)
# im = preprocess(image_files, use_vgg=use_vgg)
# out = model.predict(im)
# # plt.subplot(2,2,3)
# plt.subplot2grid((5,2), (3,0), rowspan=2)
# plot_curves(out, 10)
# # plt.ylim([0,12])
# plt.xlabel('Angle (degrees)')
# plt.ylabel('Response')
# image_files = get_image_file_list('./images/banana-rotations/', 'png', with_path=True)
# im = preprocess(image_files, use_vgg=use_vgg)
# out = model.predict(im)
# # plt.subplot(2,2,4)
# plt.subplot2grid((5,2), (3,1), rowspan=2)
# plot_curves(out, 10)
# # plt.ylim([0,12])
# plt.xlabel('Angle (degrees)')
# plt.tight_layout()
# plt.savefig('../figures/orientation.eps')
# plt.show()
plot_freiwald_histograms()
# # plot_logothetis_and_freiwald_tuning_data()
# remove_levels = [0,1,2]
# use_vgg = False
#
# # remove_levels = [0,1,2]
# # use_vgg = False
#
# plt.figure(figsize=(9,2*len(remove_levels)))
#
# hist_edges = np.linspace(-1, 1, 10)
# freiwalds = []
#
# for i in range(len(remove_levels)):
# if use_vgg:
# model = load_vgg(weights_path='../weights/vgg16_weights.h5', remove_level=remove_levels[i])
# else:
# model = load_net(weights_path='../weights/alexnet_weights.h5', remove_level=remove_levels[i])
#
# plt.subplot(len(remove_levels),3,(3*i)+1)
# image_files = get_image_file_list('./source-images/staple/', 'jpg', with_path=True)
# im = preprocess(image_files, use_vgg=use_vgg)
# out = model.predict(im)
# # angles = np.array(range(0,361,10))
# wrap_indices = range(18, 36) + range(19)
# plot_curves(out[wrap_indices,:], 10, kernel_len=3, angles=range(-180,181,10))
# plt.xticks([-180, -60, 60, 180])
# plt.ylabel('Response')
# # plt.title('Staple')
# if i == len(remove_levels)-1:
# plt.xlabel('Angle (degrees)')
#
#
# plt.subplot(len(remove_levels),3,(3*i)+2)
# image_files = get_image_file_list('./source-images/scooter/', 'jpg', with_path=True)
# im = preprocess(image_files, use_vgg=use_vgg)
# out = model.predict(im)
# wrap_indices = range(12,24) + range(13)
# plot_curves(out[wrap_indices,:], 10, kernel_len=3, angles=range(-180,181,15))
# plt.xticks([-180, -60, 60, 180])
# # plt.title('Scooter')
# if i == len(remove_levels)-1:
# plt.xlabel('Angle (degrees)')
#
# plt.subplot(len(remove_levels),3,(3*i)+3)
# image_files = get_image_file_list('./source-images/head/', 'jpg', with_path=True)
# im = preprocess(image_files, use_vgg=use_vgg)
# out = model.predict(im)
# wrap_indices = range(12,24) + range(13)
# plot_curves(out[wrap_indices,:], 10, kernel_len=3, angles=range(-180,181,15))
# plt.xticks([-180, -60, 60, 180])
# # plt.title('Head')
# if i == len(remove_levels)-1:
# plt.xlabel('Angle (degrees)')
#
# fd = freiwald_depths(out)
# h, e = np.histogram(fd, hist_edges)
# h = h.astype(float)
# h = h / np.sum(h)
# freiwalds.append(h)
#
# plt.tight_layout()
# plt.savefig('../figures/orientation3d.eps')
# plt.show()
#
# plt.figure(figsize=(3,2*len(remove_levels)))
# for i in range(len(remove_levels)):
# plt.subplot(len(remove_levels),1,i+1)
# plt.bar(hist_edges[:-1]+.02, freiwalds[i], width=.2-.04, color=[.5,.5,.5])
# plt.xlim([-1, 1])
# plt.ylim([0, .55])
# plt.ylabel('Fraction of units')
#
# plt.xlabel('Head orientation tuning depth')
# plt.tight_layout()
# plt.savefig('../figures/orientation-freiwald-net.eps')
# plt.show()
# plt.figure(figsize=(7,3))
# n = 15
# kernel_len = 3
# angles = range(0,361,10)
# image_files = get_image_file_list('./source-images/staple/', 'jpg', with_path=True)
# im = preprocess(image_files)
# out = model.predict(im)
# plt.subplot(1,2,1)
# plot_curves(out, n, kernel_len=kernel_len, angles=angles, normalize=True)
# plt.ylabel('Response')
# plt.ylim([0,1])
# plt.title('CNN')
#
# fake = np.zeros((out.shape[0], n))
# np.random.seed(1)
# prefs = 360.*np.random.rand(n)
# i = 0
# widths = np.zeros(n)
# while i < n:
# width = 30. + 15. * np.random.randn()
# if width > 1:
# widths[i] = width
# i = i + 1
# print(widths)
#
# for i in range(n):
# fake[:,i] = np.exp(-(angles-prefs[i])**2 / 2 / widths[i]**2)
#
#
# plt.subplot(1,2,2)
# plot_curves(fake, n, kernel_len=kernel_len, angles=angles, normalize=True)
# plt.title('Empirical')
# plt.ylim([0,1])
#
# plt.tight_layout()
# plt.savefig('../figures/orientation-salman.eps')
# plt.show()
| {
"repo_name": "bptripp/it-cnn",
"path": "tuning/orientation.py",
"copies": "1",
"size": "10458",
"license": "mit",
"hash": -499343919266384960,
"line_mean": 31.3777089783,
"line_max": 107,
"alpha_frac": 0.5720022949,
"autogenerated": false,
"ratio": 2.853478854024557,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8906378837938125,
"avg_score": 0.0038204621972864256,
"num_lines": 323
} |
__author__ = 'bptripp'
import numpy as np
from os.path import join
import scipy
import cPickle
from keras.optimizers import Adam
from data import load_all_params
from keras.models import model_from_json
def get_input(object, seq_num):
image_file = object[:-4] + '-' + str(seq_num) + '-overlap.png'
X = []
image_dir = '../../grasp-conv/data/obj_overlap/'
image = scipy.misc.imread(join(image_dir, image_file))
X.append(image[:,32:48] / 255.0)
image_dir = '../../grasp-conv/data/support_overlap/'
image = scipy.misc.imread(join(image_dir, image_file))
X.append(image[:,32:48] / 255.0)
return np.array(X)
f = open('o-valid-ind.pkl')
validation_indices = cPickle.load(f)
f.close()
model = model_from_json(open('o-model-architecture.json').read())
model.load_weights('o-model-weights.h5')
adam = Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-08)
model.compile(loss='binary_crossentropy', optimizer=adam)
objects, gripper_pos, gripper_orient, labels = load_all_params('../../grasp-conv/data/output_data.csv')
seq_nums = np.arange(len(objects)) % 1000 #exactly 1000 per object in above file (dated March 18)
labels = np.array(labels)[:,np.newaxis]
Y_valid = labels[validation_indices,:]
X_valid = []
for ind in validation_indices:
X_valid.append(get_input(objects[ind], seq_nums[ind]))
X_valid = np.array(X_valid)
predictions = model.predict(X_valid, batch_size=32, verbose=0)
print(predictions)
f = open('o-predict.pkl', 'wb')
cPickle.dump((predictions, Y_valid), f)
f.close()
| {
"repo_name": "bptripp/grasp-convnet",
"path": "py/overlap_check.py",
"copies": "1",
"size": "1534",
"license": "mit",
"hash": -1824734868123990300,
"line_mean": 27.4074074074,
"line_max": 103,
"alpha_frac": 0.6870925684,
"autogenerated": false,
"ratio": 2.8407407407407406,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8921821947176998,
"avg_score": 0.021202272392748585,
"num_lines": 54
} |
__author__ = 'bptripp'
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Flatten
from keras.layers.convolutional import Convolution2D, MaxPooling2D
"""
Initialization of CNNs via clustering of inputs and convex optimization
of outputs.
"""
def sigmoid(x, centre, gain):
y = 1 / (1 + np.exp(-gain*(x-centre)))
return y
def gaussian(x, mu, sigma):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sigma, 2.)))
def get_sigmoid_params(false_samples, true_samples, do_plot=False):
"""
Find gain and bias for sigmoid function that approximates probability
of class memberships. Probability based on Bayes' rule & gaussian
model of samples from each class.
"""
false_mu = np.mean(false_samples)
false_sigma = np.std(false_samples)
true_mu = np.mean(true_samples)
true_sigma = np.std(true_samples)
lowest = np.minimum(np.min(false_samples), np.min(true_samples))
highest = np.maximum(np.max(false_samples), np.max(true_samples))
a = np.arange(lowest, highest, (highest-lowest)/25)
p_x_false = gaussian(a, false_mu, false_sigma)
p_x_true = gaussian(a, true_mu, true_sigma)
p_x = p_x_true + p_x_false
p_true = p_x_true / p_x
popt, _ = curve_fit(sigmoid, a, p_true)
centre, gain = popt[0], popt[1]
if do_plot:
plt.hist(false_samples, a)
plt.hist(true_samples, a)
plt.plot(a, 100*sigmoid(a, centre, gain))
plt.plot(a, 100*p_true)
plt.title('centre: ' + str(centre) + ' gain: ' + str(gain))
plt.show()
return centre, gain
def check_sigmoid():
n = 1000
false_samples = 1 + .3*np.random.randn(n)
true_samples = -1 + 1*np.random.randn(n)
centre, gain = get_sigmoid_params(false_samples, true_samples, do_plot=True)
def get_convolutional_prototypes(samples, shape, patches_per_sample=5):
assert len(samples.shape) == 4
assert len(shape) == 4
wiggle = (samples.shape[2]-shape[2], samples.shape[3]-shape[3])
patches = []
for sample in samples:
for i in range(patches_per_sample):
corner = (np.random.randint(0, wiggle[0]), np.random.randint(0, wiggle[1]))
patches.append(sample[:,corner[0]:corner[0]+shape[2],corner[1]:corner[1]+shape[3]])
patches = np.array(patches)
flat = np.reshape(patches, (patches.shape[0], -1))
km = KMeans(shape[0])
km.fit(flat)
kernels = km.cluster_centers_
# normalize product of centre and corresponding kernel
for i in range(kernels.shape[0]):
kernels[i,:] = kernels[i,:] / np.linalg.norm(kernels[i,:])
return np.reshape(kernels, shape)
def get_dense_prototypes(samples, n):
km = KMeans(n)
km.fit(samples)
return km.cluster_centers_
def check_get_prototypes():
samples = np.random.rand(1000, 2, 28, 28)
prototypes = get_convolutional_prototypes(samples, (20,2,5,5))
print(prototypes.shape)
samples = np.random.rand(900, 2592)
prototypes = get_dense_prototypes(samples, 64)
print(prototypes.shape)
def get_discriminant(samples, labels):
lda = LinearDiscriminantAnalysis(solver='eigen', shrinkage='auto')
lda.fit(samples, labels)
return lda.coef_[0]
def check_discriminant():
n = 1000
labels = np.random.rand(n) < 0.5
samples = np.zeros((n,2))
for i in range(len(labels)):
if labels[i] > 0.5:
samples[i,:] = np.array([0,1]) + 1*np.random.randn(1,2)
else:
samples[i,:] = np.array([-2,-1]) + .5*np.random.randn(1,2)
coeff = get_discriminant(samples, labels)
plt.figure(figsize=(10,5))
plt.subplot(1,2,1)
plt.scatter(samples[labels>.5,0], samples[labels>.5,1], color='g')
plt.scatter(samples[labels<.5,0], samples[labels<.5,1], color='r')
plt.plot([-coeff[0], coeff[0]], [-coeff[1], coeff[1]], color='k')
plt.subplot(1,2,2)
get_sigmoid_params(np.dot(samples[labels<.5], coeff),
np.dot(samples[labels>.5], coeff),
do_plot=True)
plt.show()
def init_model(model, X_train, Y_train):
if not (isinstance(model.layers[-1], Activation) \
and model.layers[-1].activation.__name__ == 'sigmoid'\
and isinstance(model.layers[-2], Dense)):
raise Exception('This does not look like an LDA-compatible network, which is all we support')
for i in range(len(model.layers)-2):
if isinstance(model.layers[i], Convolution2D):
inputs = get_inputs(model, X_train, i)
w, b = model.layers[i].get_weights()
w = get_convolutional_prototypes(inputs, w.shape)
b = .1 * np.ones_like(b)
model.layers[i].set_weights([w,b])
if isinstance(model.layers[i], Dense):
inputs = get_inputs(model, X_train, i)
w, b = model.layers[i].get_weights()
w = get_dense_prototypes(inputs, w.shape[1]).T
b = .1 * np.ones_like(b)
model.layers[i].set_weights([w,b])
inputs = get_inputs(model, X_train, len(model.layers)-3)
coeff = get_discriminant(inputs, Y_train)
centre, gain = get_sigmoid_params(np.dot(inputs[Y_train<.5], coeff),
np.dot(inputs[Y_train>.5], coeff))
w = coeff*gain
w = w[:,np.newaxis]
b = np.array([-centre])
model.layers[-2].set_weights([w,b])
sigmoid_inputs = get_inputs(model, X_train, len(model.layers)-1)
plt.figure()
plt.subplot(2,1,1)
bins = np.arange(np.min(Y_train), np.max(Y_train))
plt.hist(sigmoid_inputs[Y_train<.5])
plt.subplot(2,1,2)
plt.hist(sigmoid_inputs[Y_train>.5])
plt.show()
def get_inputs(model, X_train, layer):
if layer == 0:
return X_train
else:
partial_model = Sequential(layers=model.layers[:layer])
partial_model.compile('sgd', 'mse')
return partial_model.predict(X_train)
if __name__ == '__main__':
# check_sigmoid()
# check_get_prototypes()
# check_discriminant()
import cPickle
f = file('../data/bowl-test.pkl', 'rb')
# f = file('../data/depths/24_bowl-29-Feb-2016-15-01-53.pkl', 'rb')
d, bd, l = cPickle.load(f)
f.close()
d = d - np.mean(d.flatten())
d = d / np.std(d.flatten())
# n = 900
n = 90
X_train = np.zeros((n,1,80,80))
X_train[:,0,:,:] = d[:n,:,:]
Y_train = l[:n]
model = Sequential()
model.add(Convolution2D(64,9,9,input_shape=(1,80,80)))
model.add(Activation('relu'))
model.add(MaxPooling2D())
# model.add(Convolution2D(64,3,3))
# model.add(Activation('relu'))
# model.add(MaxPooling2D())
model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dense(1))
model.add(Activation('sigmoid'))
init_model(model, X_train, Y_train)
# from visualize import plot_kernels
# plot_kernels(model.layers[0].get_weights()[0])
| {
"repo_name": "bptripp/grasp-convnet",
"path": "py/cninit.py",
"copies": "1",
"size": "7083",
"license": "mit",
"hash": 9001662641487659000,
"line_mean": 30.9054054054,
"line_max": 101,
"alpha_frac": 0.6162642948,
"autogenerated": false,
"ratio": 3.0822454308093996,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.41985097256093995,
"avg_score": null,
"num_lines": null
} |
__author__ = 'bptripp'
import numpy as np
from scipy.optimize import newton
from scipy.signal import convolve2d
import matplotlib.pyplot as plt
# Barrett hand dimensions from http://www.barrett.com/images/HandDime4.gif
# Fingers don't extend fully, max 40deg from straight. First segment .07m; second .058m
# I have estimated the hand origin in MeshLab from a mesh exported from V-REP
def finger_path_template(fov, im_width, camera_offset, finger_width=.025):
"""
:param fov: camera field of view (radians!!!)
:param im_width: pixels
:param camera_offset: distance of camera behind hand
:return: distance image of the intersection volume of Barrett hand
"""
# pixels = range(im_width/2)
pixels = range(-im_width/4, im_width/2) # cross centre
rads_per_pixel = fov / im_width;
angles = rads_per_pixel * (np.array(pixels).astype(float) + 0.5)
single_finger_xyz = (0.,.0396,.0302)
double_finger_xyz = (0.025,.0604,.0302)
single_depths = [] #lone finger
double_depths = [] #pair of fingers on other side
for angle in angles:
single_depths.append(finger_depth(angle, camera_offset, finger_yz=single_finger_xyz[1:]))
double_depths.append(finger_depth(angle, camera_offset, finger_yz=double_finger_xyz[1:]))
template = np.zeros((im_width,im_width))
for i in range(len(pixels)):
if single_depths[i] > 0:
finger_half_width_rad = np.arctan(finger_width/2./single_depths[i])
finger_half_width_pixels = finger_half_width_rad / rads_per_pixel
min_finger = int(np.floor(im_width/2-finger_half_width_pixels+.5))
max_finger = int(np.ceil(im_width/2+finger_half_width_pixels+.5))
template[im_width/2-1-pixels[i],min_finger:max_finger] = single_depths[i] #TODO: clean up offset
if double_depths[i] > 0:
finger_x_pixels = np.arctan(double_finger_xyz[0]/double_depths[i]) / rads_per_pixel # x offset of paired fingers
min_finger = int(np.floor(im_width/2+finger_x_pixels-finger_half_width_pixels+.5))
max_finger = int(np.ceil(im_width/2+finger_x_pixels+finger_half_width_pixels+.5))
template[im_width/2+pixels[i],min_finger:max_finger] = double_depths[i]
min_finger = int(np.floor(im_width/2-finger_x_pixels-finger_half_width_pixels+.5))
max_finger = int(np.ceil(im_width/2-finger_x_pixels+finger_half_width_pixels+.5))
template[im_width/2+pixels[i],min_finger:max_finger] = double_depths[i]
return template
def finger_depth(camera_angle, camera_offset, finger_length=.12, finger_yz=(.05,0.013), finger_ext=.31):
# finger_ext: angle from finger CoR to tip at max extension
y0 = finger_yz[0]
z0 = finger_yz[1]
l = finger_length
max_angle = np.arctan((y0+l*np.cos(finger_ext))/(z0+camera_offset+l*np.sin(finger_ext)))
# this seems like a reasonable place to stop
min_angle = np.arctan((y0+l*np.cos(0.75*np.pi))/(z0+camera_offset+l*np.sin(0.75*np.pi)))
result = 0
# if camera_angle > -1e-6 and camera_angle < max_angle:
if camera_angle > min_angle and camera_angle < max_angle:
# find corresponding finger angle
f = lambda b: (y0+l*np.sin(b))/(z0+camera_offset+l*np.cos(b)) - np.tan(camera_angle)
b = newton(f, np.pi/4.)
z = z0 + camera_offset + l*np.cos(b)
y = y0 + l*np.sin(b)
result = np.sqrt(y**2+z**2)
return result
def calculate_metric_map(depth_map, finger_path, direction, saturation_distance=.02, box_size=3):
"""
An intermediate step in calculation of grip metrics. It isn't necessary to calculate
this result separately except that decomposing calculation of metrics in this way
may simplify deep network training.
The same metrics could be calculated from various related maps. This one is chosen because
it has fairly local features that should be easy for a network to approximate.
"""
finger_width = np.round(np.mean(np.sum(finger_path > 0, axis=0)))
overlap = np.maximum(0, finger_path - depth_map)
overlap = np.minimum(saturation_distance, overlap)
overlap = overlap[::direction,:]
running_max = np.zeros_like(overlap)
for i in range(overlap.shape[0]):
start = np.maximum(0,i)
finish = np.minimum(overlap.shape[0],i+1)
running_max[i,:] = np.max(overlap[start:finish,:], axis=0)
window = np.ones((box_size,finger_width))
window = window / np.sum(window*saturation_distance) # normalize so that max convolution result is 1
result = convolve2d(running_max, window, mode='same')
return result[::direction,:]
def calculate_grip_metrics(depth_map, finger_path, saturation_distance=.02, box_size=3):
overlap = np.maximum(0, finger_path - depth_map)
# find first overlap from outside to centre in three regions
s = depth_map.shape
regions = [[s[0],s[0]/2,0,s[1]/2],
[s[0],s[0]/2,s[1]/2,s[1]],
[0,s[0]/2,s[1]/4,3*s[1]/4]]
close_directions = [-1,-1,1]
intersections = []
qualities = []
for region, direction in zip(regions, close_directions):
region_overlap = overlap[region[0]:region[1]:direction,region[2]:region[3]]
#running max to avoid penalizing grasping outside of concave shape ...
# region_overlap = np.maximum.accumulate(region_overlap, axis=1)
region_overlap = np.maximum.accumulate(region_overlap, axis=0)
# p = np.sum(region_overlap, axis=0)
p = np.sum(region_overlap, axis=1)
# print(p)
if True in (p>0).tolist():
intersection = (p>0).tolist().index(True)
else:
intersection = None
intersections.append(intersection)
region_finger = finger_path[region[0]:region[1]:direction,region[2]:region[3]]
region_finger = saturation_distance * np.array(region_finger > 0).astype(float)
region_overlap = np.minimum(region_overlap, saturation_distance)
if intersection is None:
quality = 0
else:
# sub_region_overlap = region_overlap[:,intersection:intersection+box_size]
# sub_region_finger = region_finger[:,intersection:intersection+box_size]
sub_region_overlap = region_overlap[intersection:intersection+box_size,:]
sub_region_finger = region_finger[intersection:intersection+box_size,:]
quality = np.sum(sub_region_overlap.flatten()) / np.sum(sub_region_finger.flatten())
# plt.imshow(sub_region_finger)
# plt.show()
qualities.append(quality)
# print(intersections)
# print(qualities)
#
# from mpl_toolkits.mplot3d import axes3d, Axes3D
# X = np.arange(0, len(depth_map))
# Y = np.arange(0, len(depth_map))
# X, Y = np.meshgrid(X, Y)
# fig = plt.figure()
# ax = fig.add_subplot(1,1,1,projection='3d')
# ax.plot_wireframe(X, Y, overlap)
# plt.show()
return intersections, qualities
def check_overlap_range(image_dir='../../grasp-conv/data/obj_depths', im_width=80, camera_offset=.45, far_clip=.8):
from data import load_all_params
import scipy
objects, gripper_pos, gripper_orient, labels = load_all_params('../../grasp-conv/data/output_data.csv')
seq_nums = np.arange(len(objects)) % 1000
from os import listdir
from os.path import isfile, join
from heuristic import finger_path_template
finger_path = finger_path_template(45.*np.pi/180., im_width, camera_offset)
max_overlaps = []
for object, seq_num in zip(objects, seq_nums):
filename = join(image_dir, object[:-4] + '-' + str(seq_num) + '.png')
image = scipy.misc.imread(filename)
rescaled_distance = image / 255.0
distance = rescaled_distance*(far_clip-camera_offset)+camera_offset
max_overlaps.append(np.max(finger_path - distance))
return max_overlaps, labels
if __name__ == '__main__':
camera_offset=.45
near_clip=.25
far_clip=.8
fov = 45.*np.pi/180.
im_width=80
template = finger_path_template(fov, im_width, camera_offset)
plt.imshow(template)
plt.show()
# import scipy
# image = scipy.misc.imread('../../grasp-conv/data/obj_depths/1_Coffeecup_final-03-Mar-2016-18-50-40-1.png')
# rescaled_distance = image / 255.0
# distance = rescaled_distance*(far_clip-camera_offset)+camera_offset
#
# finger_path = finger_path_template(45.*np.pi/180., 80, camera_offset)
# import time
# start_time = time.time()
# for i in range(100):
# mm = calculate_metric_map(distance, finger_path, 1)
# print('elapsed: ' + str(time.time() - start_time))
#
# print(np.min(mm))
# print(np.max(mm))
#
# intersections, qualities = calculate_grip_metrics(distance, finger_path)
# print(intersections)
#
# from visualize import plot_mesh
# plot_mesh(finger_path)
# from data import load_all_params
# objects, gripper_pos, gripper_orient, labels = load_all_params('../../grasp-conv/data/output_data.csv')
# # plot max overlaps (sanity check) ...
# max_overlaps, labels = check_overlap_range()
# max_overlaps = np.array(max_overlaps)
# labels = np.array(labels)
#
# import cPickle
# f = open('overlaps.pkl', 'wb')
# cPickle.dump((max_overlaps, labels), f)
# f.close()
#
# plt.plot(max_overlaps)
# plt.show()
| {
"repo_name": "bptripp/grasp-convnet",
"path": "py/heuristic.py",
"copies": "1",
"size": "9413",
"license": "mit",
"hash": -6188186780872422000,
"line_mean": 38.2208333333,
"line_max": 124,
"alpha_frac": 0.6434717943,
"autogenerated": false,
"ratio": 3.1460561497326203,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9256767204989063,
"avg_score": 0.0065521478087116536,
"num_lines": 240
} |
__author__ = 'bptripp'
import numpy as np
import cPickle
from keras.models import Sequential
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.optimizers import Adam
im_width = 80
model = Sequential()
model.add(Convolution2D(32, 9, 9, input_shape=(1,im_width,im_width), init='glorot_normal', border_mode='same'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Convolution2D(32, 3, 3, init='glorot_normal', border_mode='same'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Convolution2D(32, 3, 3, init='glorot_normal', border_mode='same'))
model.add(Activation('relu'))
model.add(Flatten())
model.add(Dense(256))
model.add(Activation('relu'))
model.add(Dropout(.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))
adam = Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-08)
# model.compile(loss='mean_squared_error', optimizer=adam)
model.compile(loss='binary_crossentropy', optimizer=adam)
f = file('../data/metrics-support.pkl', 'rb')
intersections, qualities, files = cPickle.load(f)
f.close()
#TODO: len(train_indices) + len(validation_indices) sometimes at random is slightly > len(files)
n = len(files)
validation_indices = np.random.randint(0, n, 500)
s = set(validation_indices)
train_indices = [x for x in range(n) if x not in s]
intersections = np.array(intersections)
collisions = np.where(intersections == np.array(None), 0, intersections)
collisions = np.minimum(np.max(collisions, axis=1), 1)
print(collisions.shape)
from os.path import join
import scipy
def get_input(image_file):
image_dir = '../../grasp-conv/data/support_depths/'
image = scipy.misc.imread(join(image_dir, image_file))
rescaled_distance = image / 255.0
return 1.0 - rescaled_distance # I think this is a good closeup disparity-like representation
Y_valid = collisions[validation_indices]
X_valid = []
for ind in validation_indices:
X_valid.append(get_input(files[ind]))
X_valid = np.array(X_valid)
X_valid = X_valid[:,np.newaxis,:,:]
def generate_XY():
while 1:
ind = train_indices[np.random.randint(len(train_indices))]
Y = np.zeros((1,1))
Y[0] = collisions[ind]
X = get_input(files[ind])
X = X[np.newaxis,np.newaxis,:,:]
yield (X, Y)
h = model.fit_generator(generate_XY(),
samples_per_epoch=500, nb_epoch=500,
validation_data=(X_valid, Y_valid))
f = file('collision-history.pkl', 'wb')
cPickle.dump(h, f)
f.close()
| {
"repo_name": "bptripp/grasp-convnet",
"path": "py/collision_model.py",
"copies": "1",
"size": "2567",
"license": "mit",
"hash": -644877019632732200,
"line_mean": 31.4936708861,
"line_max": 111,
"alpha_frac": 0.7051032333,
"autogenerated": false,
"ratio": 2.913734392735528,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9016633545075702,
"avg_score": 0.020440816191965208,
"num_lines": 79
} |
__author__ = 'bptripp'
import numpy as np
import matplotlib
matplotlib.rcParams['xtick.labelsize'] = 14
matplotlib.rcParams['ytick.labelsize'] = 14
import matplotlib.pyplot as plt
from cnn_stimuli import get_image_file_list
from alexnet import load_vgg, load_net, preprocess
# remove_level = 2
# use_vgg = False
#
# if use_vgg:
# model = load_vgg(weights_path='../weights/vgg16_weights.h5', remove_level=remove_level)
# else:
# model = load_net(weights_path='../weights/alexnet_weights.h5', remove_level=remove_level)
#
#
# from_dir = './images/simplification/from/'
# from_image_files = get_image_file_list(from_dir, 'png', with_path=True)
# from_out = model.predict(preprocess(from_image_files, use_vgg=use_vgg))
#
# to_dir = './images/simplification/to/'
# to_image_files = get_image_file_list(to_dir, 'png', with_path=True)
# to_out = model.predict(preprocess(to_image_files, use_vgg=use_vgg))
#
# other_dir = './images/simplification/other/'
# other_image_files = get_image_file_list(other_dir, 'png', with_path=True)
# other_out = model.predict(preprocess(other_image_files, use_vgg=use_vgg))
#
# #TODO: get null distribution by shuffling froms instead of using tos
#
# # baseline = np.min(np.concatenate((from_out, to_out), axis=0), axis=0)
# baseline = np.min(from_out, axis=0)
# from_out = from_out - baseline
# to_out = to_out - baseline
#
# n = 50
# n_shapes = from_out.shape[0]
# # ratios = []
# # nulls = []
# plt.figure(figsize=(6,6))
# edges = np.linspace(0, 2.0, 11)
# labels = ['plant', 'hind leg', 'cube', 'person', 'ball', 'haystack', 'pom-pom', 'apple', 'hand', 'skewer', 'bread', 'cat']
# position = 1
# ratio_fractions_over_one = np.zeros(n_shapes)
# null_fractions_over_one = np.zeros(n_shapes)
#
# unit_maxima = np.max(np.concatenate((from_out, other_out), axis=0), axis=0)
# tolerance = np.mean(unit_maxima) * .05
# print(tolerance)
#
# for i in range(n_shapes):
# # find units that respond most strongly to this shape, among "from" and "other" groups
# this_shape_preferred = np.logical_and(from_out[i,:] >= unit_maxima-tolerance, from_out[i,:] > 1)
# # print(sum(this_shape_preferred))
# ind = np.where(this_shape_preferred)
# # print(ind)
#
# # from_out[i,:]
#
# # response = from_out[i,:]
# # ind = (-from_out[i,:]).argsort()[:n]
# ratios = to_out[i,ind] / from_out[i,ind]
# nulls = []
# for j in range(1,n_shapes):
# nulls.append(to_out[np.mod(i+j, n_shapes),ind] / from_out[i,ind])
# nulls = np.array(nulls)
#
# #extra fussing to make order of panels like Tanaka
# plt.subplot(4,3,position)
# position = position + 3
# if position > 12:
# position = position - 11
#
# # print(ratios.flatten())
# ratio_counts, e = np.histogram(ratios.flatten(), edges)
# ratio_fractions = ratio_counts.astype(float) / np.sum(ratio_counts)
# null_counts, e = np.histogram(nulls.flatten(), edges)
# null_fractions = null_counts.astype(float) / np.sum(null_counts)
#
# plt.bar(edges[:-1], ratio_fractions, width=.2, color=[0,0,1])
# plt.bar(edges[:-1], -null_fractions, width=.2, color=[0.7,0.7,0.7])
# plt.xlim((0,2))
# plt.ylim((-.8,.8))
# plt.xticks([0,1,2])
# plt.yticks([-.8,-.4,0,.4,.8])
# plt.title(labels[i])
#
# if len(ratios.flatten()) == 0:
# ratio_fractions_over_one[i] = np.nan
# null_fractions_over_one[i] = np.nan
# else:
# ratio_fractions_over_one[i] = float(np.sum(ratios.flatten() > 1)) / len(ratios.flatten())
# null_fractions_over_one[i] = float(np.sum(nulls.flatten() > 1)) / len(nulls.flatten())
#
# plt.tight_layout()
#
# print('>1 ' + str(np.nanmean(ratio_fractions_over_one)) + ' ' + str(np.nanmean(null_fractions_over_one)))
#
# if use_vgg:
# plt.savefig('../figures/simplification-vgg-' + str(remove_level) + '.eps')
# else:
# plt.savefig('../figures/simplification-alexnet-' + str(remove_level) + '.eps')
#
# plt.show()
# plot fractions over one (from repeated runs)
remove_level = np.array([0,1,2])
#values from all above threshold ...
vgg_ratio_over_one = [0.117499415481, 0.0418854340439, 0.0531346631493]
vgg_null_over_one = [0.0523417204617, 0.0151203682413, 0.0246139848455]
alexnet_ratio_over_one = [0.149668638138, 0.07128067702, .0675081863766]
alexnet_null_over_one = [0.0663521248382, 0.0251136422064, 0.0279159685923]
#values from top 50 ...
# vgg_ratio_over_one = [0.146666666667, 0.123333333333, 0.115]
# vgg_null_over_one = [0.0984848484848, 0.0943939393939, 0.0916666666667]
# alexnet_ratio_over_one = [0.166666666667, 0.116666666667, 0.106666666667]
# alexnet_null_over_one = [0.0763636363636, 0.050303030303, 0.0604545454545]
plt.figure(figsize=(6,2))
plt.subplot(1,2,1)
plt.plot(-remove_level, vgg_ratio_over_one, color='b')
plt.plot(-remove_level, vgg_null_over_one, color='k')
plt.ylim([0,.2])
plt.title('VGG-16')
plt.subplot(1,2,2)
plt.plot(-remove_level, alexnet_ratio_over_one, color='b')
plt.plot(-remove_level, alexnet_null_over_one, color='k')
plt.ylim([0,.2])
plt.title('Alexnet')
# plt.xlabel('Distance from output (layers)')
plt.tight_layout()
plt.savefig('../figures/simplification-over-one.eps')
plt.show()
| {
"repo_name": "bptripp/it-cnn",
"path": "tuning/simplification.py",
"copies": "1",
"size": "5168",
"license": "mit",
"hash": 8056749729226095000,
"line_mean": 36.4492753623,
"line_max": 124,
"alpha_frac": 0.6557662539,
"autogenerated": false,
"ratio": 2.5647642679900744,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.3720530521890074,
"avg_score": null,
"num_lines": null
} |
__author__ = 'bptripp'
import numpy as np
import matplotlib.pyplot as plt
import cPickle
from quaternion import angle_between_quaterions
# def interpolate(point, angle, points, angles, values, sigma_p=.01, sigma_a=(4*np.pi/180)):
# """
# Gaussian kernel smoothing.
# """
# # q = to_quaternion(get_rotation_matrix(point, angle))
# # print(angle)
#
# weights = np.zeros(len(values))
# # foo = np.zeros(len(values))
# # bar = np.zeros(len(values))
# for i in range(len(values)):
# # q_i = to_quaternion(get_rotation_matrix(points[:,i], angles[:,i]))
#
# # print(q_i)
#
# # angle = angle_between_quaterions(q, q_i)
# # print(angle)
#
# position_distance = np.linalg.norm(point - points[:,i])
# angle_distance = angle[2] - angles[2,i];
#
# # weights[i] = np.exp( -(angle**2/2/sigma_a**2) )
# weights[i] = np.exp( -(angle_distance**2/2/sigma_a**2 + position_distance**2/2/sigma_p**2) )
# # weights[i] = np.exp( -(angle**2/2/sigma_a**2 + distance**2/2/sigma_p**2) )
# # foo[i] = np.exp( -(angle**2/2/sigma_a**2) )
# # bar[i] = np.exp( -(distance**2/2/sigma_p**2) )
#
# # print(weights)
# # print(np.sum(weights))
# # print(np.sum(foo))
# # print(np.sum(bar))
# return np.sum(weights * np.array(values)) / np.sum(weights)
def interpolate(quaternion, distance, quaternions, distances, values, sigma_a=(4*np.pi/180), sigma_d=.01):
"""
Gaussian kernel smoothing.
"""
weights = np.zeros(len(values))
angle_threshold = np.cos(1.25*sigma_a) # I think this corresponds to twice this angle between quaternions
distance_threshold = 2.5*sigma_d
# attempt fast estimate (only considering within-threshold points) ...
c = 0
for i in range(len(values)):
distance_difference = np.abs(distance - distances[i])
if distance_difference < distance_threshold and np.dot(quaternion, quaternions[i]) > angle_threshold:
c += 1
angle_difference = np.abs(angle_between_quaterions(quaternion, quaternions[i]))
weights[i] = np.exp( -(angle_difference**2/2/sigma_a**2 + distance_difference**2/2/sigma_d**2) )
# slow estimate if not enough matches ...
# print(c)
if c <= 3:
# print('slow estimate ' + str(c))
for i in range(len(values)):
distance_difference = np.abs(distance - distances[i])
angle_difference = np.abs(angle_between_quaterions(quaternion, quaternions[i]))
weights[i] = np.exp( -(angle_difference**2/2/sigma_a**2 + distance_difference**2/2/sigma_d**2) )
# print(weights)
# print(values)
return np.sum(weights * np.array(values)) / np.sum(weights)
def check_interpolate():
from perspective import get_quaternion_distance
point = np.array([1e-6,.1,.1])
angle = np.array([0,0,.9])
points = np.array([[1e-6,.1,.1], [1e-6,.12,.1]]).T
angles = np.array([[0,0,1], [0,0,1]]).T
values = np.array([0,1])
quaternion, distance = get_quaternion_distance(point[:,np.newaxis], angle[:,np.newaxis])
quaternions, distances = get_quaternion_distance(points, angles)
# print(quaternion)
# print(distance)
# print(quaternions)
# print(distances)
# estimate = interpolate(point, angle, points, angles, values, sigma_p=.01, sigma_a=(4*np.pi/180))
estimate = interpolate(quaternion[0], distance[0], quaternions, distances, values, sigma_d=.01, sigma_a=(4*np.pi/180))
print(estimate)
def test_interpolation_accuracy(points, angles, metrics, n_examples):
"""
Compare interpolated vs. actual metrics by leaving random
examples out of interpolation set and estimating them.
"""
from perspective import get_quaternion_distance
quaternions, distances = get_quaternion_distance(points, angles)
actuals = []
interpolateds = []
for i in range(n_examples):
print(i)
one = np.random.randint(0, len(metrics))
others = range(one)
others.extend(range(one+1, len(metrics)))
others = np.array(others)
actuals.append(metrics[one])
interpolated = interpolate(quaternions[one,:], distances[one], quaternions[others,:], distances[others], metrics[others],
sigma_d=.01, sigma_a=(8*np.pi/180))
interpolateds.append(interpolated)
# print(interpolated - metrics[one])
# print(np.corrcoef(actuals, interpolateds))
return actuals, interpolateds
def plot_interp_error_vs_density():
with open('spatula-perspectives-smoothed.pkl', 'rb') as f:
(points, angles, metrics, collisions, smoothed) = cPickle.load(f)
metrics = np.array(metrics)
smoothed = np.array(smoothed)
numbers = [250, 500, 1000, 2000, 4000]
metric_errors = []
smoothed_errors = []
for n in numbers:
actuals, interpolateds = test_interpolation_accuracy(points[:,:n], angles[:,:n], metrics[:n], 500)
metric_errors.append(np.mean( (np.array(actuals)-np.array(interpolateds))**2 )**.5)
actuals, interpolateds = test_interpolation_accuracy(points[:,:n], angles[:,:n], smoothed[:n], 500)
smoothed_errors.append(np.mean( (np.array(actuals)-np.array(interpolateds))**2 )**.5)
plt.plot(numbers, smoothed_errors)
plt.plot(numbers, metric_errors)
plt.show()
if __name__ == '__main__':
# check_interpolate()
plot_interp_error_vs_density()
| {
"repo_name": "bptripp/grasp-convnet",
"path": "py/interpolate.py",
"copies": "1",
"size": "5452",
"license": "mit",
"hash": -7175818093723811000,
"line_mean": 36.0884353741,
"line_max": 129,
"alpha_frac": 0.6214233309,
"autogenerated": false,
"ratio": 3.1845794392523366,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9283599713418187,
"avg_score": 0.004480611346829962,
"num_lines": 147
} |
__author__ = 'bptripp'
import numpy as np
def to_quaternion(rotation_matrix):
# from Siciliano & Khatib pg. 12 and quaternion.m by Tincknell
r = rotation_matrix
# e0 = .5 * np.sqrt(1 + r[0][0] + r[1][1] + r[2][2])
e0 = .5 * np.sqrt(np.maximum(0, r[0][0] + r[1][1] + r[2][2] + 1))
if e0 == 0:
e1 = np.sqrt(np.maximum(0, -0.5 * (r[1][1] + r[2][2]))) * np.sign(-r[1][2])
e2 = np.sqrt(np.maximum(0, -0.5 * (r[0][0] + r[2][2]))) * np.sign(-r[0][2])
e3 = np.sqrt(np.maximum(0, -0.5 * (r[0][0] + r[1][1]))) * np.sign(-r[0][1])
else:
e1 = (r[2][1] - r[1][2]) / (4*e0)
e2 = (r[0][2] - r[2][0]) / (4*e0)
e3 = (r[1][0] - r[0][1]) / (4*e0)
return np.array([e0,e1,e2,e3])
"""
This is from quaternion.m by Mark Tincknell
function eout = RotMat2e( R )
% function eout = RotMat2e( R )
% One Rotation Matrix -> one quaternion
eout = zeros(4,1);
if ~all( all( R == 0 ))
eout(1) = 0.5 * sqrt( max( 0, R(1,1) + R(2,2) + R(3,3) + 1 ));
if eout(1) == 0
eout(2) = sqrt( max( 0, -0.5 *( R(2,2) + R(3,3) ))) * sgn( -R(2,3) );
eout(3) = sqrt( max( 0, -0.5 *( R(1,1) + R(3,3) ))) * sgn( -R(1,3) );
eout(4) = sqrt( max( 0, -0.5 *( R(1,1) + R(2,2) ))) * sgn( -R(1,2) );
else
eout(2) = 0.25 *( R(3,2) - R(2,3) )/ eout(1);
eout(3) = 0.25 *( R(1,3) - R(3,1) )/ eout(1);
eout(4) = 0.25 *( R(2,1) - R(1,2) )/ eout(1);
end
end
end % RotMat2e
"""
def from_quaternion(e):
# from http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToMatrix/
rm = [[1-2*e[2]**2-2*e[3]**2, 2*e[1]*e[2]-2*e[3]*e[0], 2*e[1]*e[3]+2*e[2]*e[0]],
[2*e[1]*e[2]+2*e[3]*e[0], 1-2*e[1]**2-2*e[3]**2, 2*e[2]*e[3]-2*e[1]*e[0]],
[2*e[1]*e[3]-2*e[2]*e[0], 2*e[2]*e[3]+2*e[1]*e[0], 1-2*e[1]**2-2*e[2]**2]]
return np.array(rm)
def quaterion_product(e1, e2):
# from https://en.wikipedia.org/wiki/Quaternion
result = [
e1[0]*e2[0] - e1[1]*e2[1] - e1[2]*e2[2] - e1[3]*e2[3],
e1[0]*e2[1] + e1[1]*e2[0] + e1[2]*e2[3] - e1[3]*e2[2],
e1[0]*e2[2] - e1[1]*e2[3] + e1[2]*e2[0] + e1[3]*e2[1],
e1[0]*e2[3] + e1[1]*e2[2] - e1[2]*e2[1] + e1[3]*e2[0]
]
return np.array(result)
def quaternion_conj(e):
return np.array([e[0], -e[1], -e[2], -e[3]])
def angle_between_quaterions(e1, e2):
# from http://math.stackexchange.com/questions/90081/quaternion-distance
# return np.arccos(2*(e1[0]*e2[0]+e1[1]*e2[1]+e1[2]*e2[2]+e1[3]*e2[3])-1)
# from http://math.stackexchange.com/questions/167827/compute-angle-between-quaternions-in-matlab
z = quaterion_product(e1, quaternion_conj(e2))
# print(z[0])
return 2*np.arccos(np.clip(z[0], -1, 1))
def difference_between_quaternions(e1, e2):
"""
TODO: look this up when internet is back online
:param e1: From here
:param e2: To here
:return: Quaternion of rotation
"""
# print(e1)
# print(e2)
guess = quaterion_product(quaternion_conj(e1), e2)
# print(guess)
r1 = from_quaternion(e1)
r2 = from_quaternion(e2)
guess2 = to_quaternion(np.dot(np.linalg.inv(r1), r2))
# print(guess2)
p = np.array([0, .2, -.4, 1.1])
# print(quaterion_product(guess, quaterion_product(p, quaternion_conj(guess))))
# print(quaterion_product(guess2, quaterion_product(p, quaternion_conj(guess2))))
return guess2
def equal(e1, e2, tol=1e-6):
# TODO: account for double cover
equal = True
for i in range(4):
if e1[i]-e2[i] > tol:
equal = False
return equal
def check_quaternion():
r = np.array([[0.86230895, 0.20974727, -0.46090059],
[ 0.50269225, -0.4642552, 0.72922398],
[-0.06102276, -0.86050752, -0.50576974]])
error = r - from_quaternion(to_quaternion(r))
assert np.std(error.flatten()) < 1e-6
def check_difference():
# r1 = np.array([[0.86230895, 0.20974727, -0.46090059],
# [ 0.50269225, -0.4642552, 0.72922398],
# [-0.06102276, -0.86050752, -0.50576974]])
r1 = np.array([[0.31578947, -0.9486833, -0.01664357],
[-0.94736842, -0.31622777, 0.0499307],
[-0.05263158, 0., -0.998614]])
r2 = np.array([[1, 0, 0], [0, np.cos(np.pi), -np.sin(np.pi)], [0, np.sin(np.pi), np.cos(np.pi)]])
# print(r2)
difference_between_quaternions(to_quaternion(r1), to_quaternion(r2))
r3 = np.array([[1, 0, 0], [0, np.cos(np.pi/2), -np.sin(np.pi/2)], [0, np.sin(np.pi/2), np.cos(np.pi/2)]])
d = difference_between_quaternions(to_quaternion(r3), to_quaternion(r2))
# print(d)
# print(to_quaternion(r3))
assert equal(d, to_quaternion(r3))
if __name__ == '__main__':
# check_quaternion()
check_difference()
# r1 = np.array([[0.86230895, 0.20974727, -0.46090059],
# [ 0.50269225, -0.4642552, 0.72922398],
# [-0.06102276, -0.86050752, -0.50576974]])
# r2 = np.array([[1, 0, 0], [0, np.cos(np.pi), -np.sin(np.pi)], [0, np.sin(np.pi), np.cos(np.pi)]])
# # a = .5*np.pi
# r3 = np.array([[1, 0, 0], [0, np.cos(a), -np.sin(a)], [0, np.sin(a), np.cos(a)]])
# e1 = to_quaternion(r1)
# e2 = to_quaternion(r2)
# e3 = to_quaternion(r3)
# # print(e1)
# # print(e2)
# # print(np.linalg.norm(e1))
#
# print(np.dot(e2,e3))
| {
"repo_name": "bptripp/grasp-convnet",
"path": "py/quaternion.py",
"copies": "1",
"size": "5300",
"license": "mit",
"hash": 8663867377050157000,
"line_mean": 33.1935483871,
"line_max": 109,
"alpha_frac": 0.5320754717,
"autogenerated": false,
"ratio": 2.1527213647441106,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.31847968364441104,
"avg_score": null,
"num_lines": null
} |
__author__ = 'bptripp'
import os
import csv
import numpy as np
from itertools import islice
from depthmap import *
from PIL import Image
import scipy
import scipy.misc
from depthmap import loadOBJ, Display
from heuristic import calculate_metric_map
import cPickle
import matplotlib.pyplot as plt
# class GraspDataSource(object):
#
# def __init__(self, csv_file_name, obj_directory_name, range=None, imsize=(50,50)):
# self.obj_directory_name = obj_directory_name
# self.imsize = imsize
#
# self.objfiles = []
# self.orientations = []
# self.positions = []
# self.success = []
#
# with open(csv_file_name, 'rb') as csvfile:
# r = csv.reader(csvfile, delimiter=',')
# for row in islice(r, 1, None):
# self.objfiles.append(obj_directory_name + os.path.sep + row[0])
# self.orientations.append([float(row[1]), float(row[2]), float(row[3])])
# self.positions.append([float(row[4]), float(row[5]), float(row[6])])
# self.success.append(float(row[8]))
#
# if range is not None:
# self.objfiles = self.objfiles[range[0]:range[1]]
# self.orientations = self.orientations[range[0]:range[1]]
# self.positions = self.positions[range[0]:range[1]]
# self.success = self.success[range[0]:range[1]]
#
# self.display = Display(imsize=imsize)
#
#
# def get_XY(self, n):
# ind = np.random.randint(0, len(self.objfiles), n)
# X = np.zeros((n, 1, self.imsize[0], self.imsize[1]))
# Y = np.zeros(n)
# for i in range(n):
# # print(self.objfiles[ind[i]])
# verts, faces = loadOBJ(self.objfiles[ind[i]])
# new_verts = move_vertices(self.positions[ind[i]], self.orientations[ind[i]], verts)
# self.display.set_mesh(new_verts, faces)
# X[i,0,:,:] = self.display.read_depth()
# Y[i] = self.success[ind[i]]
# return np.array(X), np.array(Y)
# class AshleyDataSource(object):
# def __init__(self):
# self.X = np.zeros((1000,1,28,28))
# for i in range(1000):
# # filename = '25_mug-02-Feb-2016-12-40-43.obj131001'
# filename = '../data/imgs/25_mug-02-Feb-2016-12-40-43.obj13' + str(1001+i) + '.png'
# im = Image.open(filename)
# self.X[i,0,:,:] = np.array(im.getdata()).reshape((28,28))
#
# for line in open('../data/labels.csv', "r"):
# vals = line.split(',')
# self.Y = map(int, vals)
#
# # normalize input
# self.X = (self.X - np.mean(self.X.flatten())) / np.std(self.X.flatten())
# def make_depth_from_gripper(obj_filename, param_filename, bottom=0.2):
# """
# Make depth images from perspective of gripper.
# """
# verts, faces = loadOBJ(obj_filename)
# verts = np.array(verts)
# min_bounding_box = np.min(verts, axis=0)
# max_bounding_box = np.max(verts, axis=0)
#
# # set bounding box horizontal centre to 0,0
# verts[:,0] = verts[:,0] - (min_bounding_box[0]+max_bounding_box[0])/2.
# verts[:,1] = verts[:,1] - (min_bounding_box[1]+max_bounding_box[1])/2.
# # set bottom of bounding box to "bottom"
# verts[:,2] = verts[:,2] + bottom - min_bounding_box[2]
#
# d = Display(imsize=(80,80))
#
# labels = []
# depths = []
# c = 0
# for line in open(param_filename, "r"):
# # print(c)
# # if c == 100:
# # break
# c = c + 1
#
# vals = line.split(',')
# gripper_pos = [float(vals[0]), float(vals[1]), float(vals[2])]
# gripper_orient = [float(vals[3]), float(vals[4]), float(vals[5])]
# rot = rot_matrix(gripper_orient[0], gripper_orient[1], gripper_orient[2])
# labels.append(int(vals[6]))
#
# d.set_camera_position(gripper_pos, rot, .4)
# d.set_mesh(verts, faces) #this mut go after set_camera_position
# depth = d.read_depth()
# depths.append(depth)
#
# d.close()
# return np.array(depths), np.array(labels)
def load_all_params(param_filename, return_power_pinch=False):
"""
Example line from file:
"104_toaster_final-18-Dec-2015-13-56-59.obj",2.99894,0.034299705,0.4714164,0.09123467,0.0384472,0.5518384,0.0880979987086634,0.0
"""
bad = [
# Ashley says these are bad after looking through V-REP images ...
'24_bowl-24-Feb-2016-17-38-53',
'24_bowl-26-Feb-2016-08-35-29',
'24_bowl-27-Feb-2016-23-52-43',
'24_bowl-29-Feb-2016-15-01-53',
'25_mug-11-Feb-2016-02-25-25',
'28_Spatula_final-10-Mar-2016-18-31-08',
'42_wineglass_final-01-Nov-2015-19-25-18',
# These somehow have two objects in V-REP images ...
'24_bowl-02-Mar-2016-07-03-29',
'24_bowl-03-Mar-2016-22-54-50',
'24_bowl-05-Mar-2016-13-53-41',
'24_bowl-07-Mar-2016-05-06-04',
# These ones may fall over a bit at simulation start (first has off depth maps, others don't) ...
'55_hairdryer_final-18-Nov-2015-13-57-47',
'55_hairdryer_final-15-Dec-2015-12-18-19',
'55_hairdryer_final-09-Dec-2015-09-54-47',
'55_hairdryer_final-19-Nov-2015-09-56-56',
'55_hairdryer_final-21-Nov-2015-05-16-08',
# These frequently do not have object at centre of depth map (various reasons possible) ...
'33_pan_final-11-Mar-2016-17-41-49',
'53_watertap_final-04-Dec-2015-01-28-24',
'53_watertap_final-06-Dec-2015-04-20-45',
'53_watertap_final-15-Nov-2015-05-08-46',
'53_watertap_final-17-Nov-2015-00-26-39',
'53_watertap_final-17-Nov-2015-15-57-57',
'53_watertap_final-19-Jan-2016-04-32-52',
'56_headphones_final-11-Nov-2015-14-14-02',
'64_tongs_final-02-Dec-2015-12-22-36',
'68_toy_final-05-Dec-2015-03-00-07',
'68_toy_final-13-Nov-2015-10-50-34',
'68_toy_final-18-Dec-2015-12-36-41',
'68_toy_final-22-Nov-2015-08-51-12',
'76_mirror_final-06-Dec-2015-03-46-18',
'77_napkinholder_final-28-Nov-2015-13-06-17',
'79_toy_dog_final-03-Dec-2015-08-15-04',
'79_toy_dog_final-20-Jan-2016-06-55-00',
'92_shell_final-26-Feb-2016-17-48-04',
'94_weight_final-27-Feb-2016-15-40-40',
'94_weight_final-29-Feb-2016-17-59-42',
'95_boots_final-01-Mar-2016-16-02-15',
'95_boots_final-01-Mar-2016-16-07-50',
'95_boots_final-02-Mar-2016-13-46-24',
'95_boots_final-02-Mar-2016-13-56-54',
'95_boots_final-15-Nov-2015-06-30-07',
'95_boots_final-20-Nov-2015-09-23-39',
'95_boots_final-21-Nov-2015-04-00-35',
'95_boots_final-23-Dec-2015-15-28-51',
'95_boots_final-28-Feb-2016-18-58-13',
'95_boots_final-28-Feb-2016-18-58-15',
'98_faucet_final-28-Feb-2016-18-32-04',
'98_faucet_final-28-Feb-2016-18-58-23',
'98_faucet_final-28-Feb-2016-18-58-25'
]
objects = []
gripper_pos = []
gripper_orient = []
labels = []
power_pinch = []
skip_count = 0
for line in open(param_filename, "r"):
vals = line.translate(None, '"\n').split(',')
if (vals[0] == 'objfilename'):
pass
elif vals[0][:-4] in bad:
skip_count += 1
else:
objects.append(vals[0])
gripper_orient.append([float(vals[1]), float(vals[2]), float(vals[3])])
gripper_pos.append([float(vals[4]), float(vals[5]), float(vals[6])])
labels.append(int(float(vals[8])))
power_pinch.append(float(vals[7]))
print('Skipped ' + str(skip_count) + '; returning ' + str(len(objects)))
if return_power_pinch:
return objects, gripper_pos, gripper_orient, labels, power_pinch
else:
return objects, gripper_pos, gripper_orient, labels
def make_depth_images(obj_name, pos, rot, obj_dir, image_dir, bottom=0.2, imsize=(80,80),
camera_offset=.45, near_clip=.25, far_clip=.8, support=False):
"""
Saves depth images from perspective of gripper as image files. Default
camera parameters make an exaggerated representation of region in front of hand.
:param obj_name: Name corresponding to .obj file (without path or extension)
:param pos: Positions of perspectives from which to make depth images
:param rot: Rotation matrices of perspectives
:param obj_dir: Directory where .obj files can be found
:param image_dir: Directory in which to store images
"""
obj_filename = obj_dir + obj_name + '.obj'
if support:
verts, faces = loadOBJ('../data/support-box.obj')
else:
verts, faces = loadOBJ(obj_filename)
verts = np.array(verts)
# minz = np.min(verts, axis=0)[2]
# verts[:,2] = verts[:,2] + bottom - minz
min_bounding_box = np.min(verts, axis=0)
max_bounding_box = np.max(verts, axis=0)
# set bounding box horizontal centre to 0,0
verts[:,0] = verts[:,0] - (min_bounding_box[0]+max_bounding_box[0])/2.
verts[:,1] = verts[:,1] - (min_bounding_box[1]+max_bounding_box[1])/2.
# set bottom of bounding box to "bottom"
verts[:,2] = verts[:,2] + bottom - min_bounding_box[2]
d = Display(imsize=imsize)
d.set_perspective(fov=45, near_clip=near_clip, far_clip=far_clip)
for i in range(len(pos)):
d.set_camera_position(pos[i], rot[i], camera_offset)
d.set_mesh(verts, faces) #this must go after set_camera_position
depth = d.read_depth()
distance = get_distance(depth, near_clip, far_clip)
rescaled_distance = np.maximum(0, (distance-camera_offset)/(far_clip-camera_offset))
imfile = image_dir + obj_name + '-' + str(i) + '.png'
Image.fromarray((255.0*rescaled_distance).astype('uint8')).save(imfile)
# scipy.misc.toimage(depth, cmin=0.0, cmax=1.0).save(imfile)
d.close()
def make_random_depths(obj_filename, param_filename, n, im_size=(40,40)):
"""
Creates a dataset of depth maps and corresponding success probabilities
at random interpolated gripper configurations.
"""
verts, faces = loadOBJ(obj_filename)
verts = np.array(verts)
minz = np.min(verts, axis=0)[2]
verts[:,2] = verts[:,2] + 0.2 - minz
points, labels = get_points(param_filename)
d = Display(imsize=im_size)
probs = []
depths = []
for i in range(n):
point = get_interpolated_point(points)
estimate, confidence = get_prob_label(points, labels, point, sigma_p=2*.001, sigma_a=2*(4*np.pi/180))
probs.append(estimate)
gripper_pos = point[:3]
gripper_orient = point[3:]
d.set_camera_position(gripper_pos, gripper_orient, .3)
d.set_mesh(verts, faces) #this must go after set_camera_position
depth = d.read_depth()
depths.append(depth)
d.close()
return np.array(depths), np.array(probs)
def get_interpolated_point(points):
"""
Creates a random point that is interpolated between a pair of nearby points.
"""
p1 = np.random.randint(0, len(points))
p2 = get_closest_index(points, p1, prob_include=.5)
mix_weight = np.random.rand()
result = points[p1]*mix_weight + points[p2]*(1-mix_weight)
return result
def get_closest_index(points, index, prob_include=1):
min_distance = 1000
closest_index = []
for i in range(len(points)):
distance = np.linalg.norm(points[i] - points[index])
if distance < min_distance and i != index and np.random.rand() < prob_include:
min_distance = distance
closest_index = i
return closest_index
def get_points(param_filename):
points = []
labels = []
for line in open(param_filename, "r"):
vals = line.split(',')
points.append([float(vals[0]), float(vals[1]), float(vals[2]),
float(vals[3]), float(vals[4]), float(vals[5])])
labels.append(int(vals[6]))
return np.array(points), labels
def get_prob_label(points, labels, point, sigma_p=.01, sigma_a=(4*np.pi/180)):
"""
Gaussian kernel smoothing of success/failure to estimate success probability.
"""
sigma_p_inv = sigma_p**-1
sigma_a_inv = sigma_a**-1
sigma_inv = np.diag([sigma_p_inv, sigma_p_inv, sigma_p_inv,
sigma_a_inv, sigma_a_inv, sigma_a_inv])
differences = points - point
weights = np.zeros(len(labels))
for i in range(len(labels)):
weights[i] = np.exp( -(1./2) * np.dot(differences[i,:], np.dot(sigma_inv, differences[i,:])) )
estimate = np.sum(weights * np.array(labels).astype(float)) / np.sum(weights)
confidence = np.sum(weights)
# print(confidence)
return estimate, confidence
# def make_random_bowl_depths():
# shapes = ['24_bowl-02-Mar-2016-07-03-29',
# '24_bowl-03-Mar-2016-22-54-50',
# '24_bowl-05-Mar-2016-13-53-41',
# '24_bowl-07-Mar-2016-05-06-04',
# '24_bowl-16-Feb-2016-10-12-27',
# '24_bowl-17-Feb-2016-22-00-34',
# '24_bowl-24-Feb-2016-17-38-53',
# '24_bowl-26-Feb-2016-08-35-29',
# '24_bowl-27-Feb-2016-23-52-43',
# '24_bowl-29-Feb-2016-15-01-53']
#
# # shapes = ['24_bowl-02-Mar-2016-07-03-29']
#
# n = 10000
# for shape in shapes:
# depths, labels = make_random_depths('../data/obj_files/' + shape + '.obj',
# '../data/params/' + shape + '.csv',
# n, im_size=(40,40))
#
# f = file('../data/' + shape + '-random.pkl', 'wb')
# cPickle.dump((depths, labels), f)
# f.close()
# def check_random_bowl_depths():
#
# # shapes = ['24_bowl-02-Mar-2016-07-03-29',
# # '24_bowl-03-Mar-2016-22-54-50',
# # '24_bowl-05-Mar-2016-13-53-41',
# # '24_bowl-07-Mar-2016-05-06-04',
# # '24_bowl-16-Feb-2016-10-12-27',
# # '24_bowl-17-Feb-2016-22-00-34',
# # '24_bowl-24-Feb-2016-17-38-53',
# # '24_bowl-26-Feb-2016-08-35-29',
# # '24_bowl-27-Feb-2016-23-52-43',
# # '24_bowl-29-Feb-2016-15-01-53']
#
# shapes = ['24_bowl-02-Mar-2016-07-03-29']
#
# f = file('../data/' + shapes[0] + '-random.pkl', 'rb')
# (depths, labels) = cPickle.load(f)
# f.close()
#
# print(labels)
#
# import matplotlib.pyplot as plt
# from mpl_toolkits.mplot3d import axes3d, Axes3D
#
# depths = depths.astype(float)
# depths[depths > np.max(depths.flatten()) - 1] = np.NaN
#
# X = np.arange(0, depths.shape[1])
# Y = np.arange(0, depths.shape[2])
# X, Y = np.meshgrid(X, Y)
# fig = plt.figure(figsize=(12,6))
# ax1 = fig.add_subplot(1, 2, 1, projection='3d')
# plt.xlabel('x')
# ax2 = fig.add_subplot(1, 2, 2, projection='3d')
# plt.xlabel('x')
# # ax = Axes3D(fig)
# # for i in range(depths.shape[0]):
# s = 5 #pixel stride
# for i in range(n):
# if labels[i] > .5:
# color = 'g'
# ax = ax1
# ax.plot_wireframe(X[::s,::s], Y[::s,::s], depths[i,::s,::s], color=color)
# else:
# color = 'r'
# ax = ax2
# if np.random.rand(1) < .5:
# ax.plot_wireframe(X[::s,::s], Y[::s,::s], depths[i,::s,::s], color=color)
# # plt.title(str(i) + ': ' + str(labels[i]))
# plt.show()
def plot_box_corners():
verts, faces = loadOBJ('../data/support-box.obj')
verts = np.array(verts)
print(verts.shape)
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D
fig = plt.figure()
ax = fig.add_subplot(1, 2, 1, projection='3d')
ax.scatter(verts[:,0], verts[:,1], verts[:,2])
plt.show()
# def save_bowl_and_box_depths():
# shapes = [
# '24_bowl-16-Feb-2016-10-12-27',
# '24_bowl-17-Feb-2016-22-00-34',
# '24_bowl-24-Feb-2016-17-38-53',
# '24_bowl-26-Feb-2016-08-35-29',
# '24_bowl-27-Feb-2016-23-52-43',
# '24_bowl-29-Feb-2016-15-01-53']
#
# import time
# for shape in shapes:
# print('Processing ' + shape)
# start_time = time.time()
# depths, labels = make_depth_from_gripper('../data/obj_files/' + shape + '.obj',
# '../data/params/' + shape + '.csv',
# bottom=0.2)
# box_depths, _ = make_depth_from_gripper('../data/support-box.obj',
# '../data/params/' + shape + '.csv',
# bottom=0)
# f = file('../data/depths/' + shape + '.pkl', 'wb')
# cPickle.dump((depths, box_depths, labels), f)
# f.close()
# print(' ' + str(time.time() - start_time) + 's')
def check_bowl_and_box_variance():
f = file('../data/depths/' + '24_bowl-16-Feb-2016-10-12-27' + '.pkl', 'rb')
depths, box_depths, labels = cPickle.load(f)
f.close()
# print(labels)
# print(depths.shape)
# print(box_depths.shape)
obj_sd = []
box_sd = []
for i in range(len(labels)):
obj_sd.append(np.std(depths[i,:,:].flatten()))
box_sd.append(np.std(box_depths[i,:,:].flatten()))
import matplotlib.pyplot as plt
plt.plot(obj_sd)
plt.plot(box_sd)
plt.show()
def plot_bowl_and_box_distance_example():
f = file('../data/depths/' + '24_bowl-16-Feb-2016-10-12-27' + '.pkl', 'rb')
depths, box_depths, labels = cPickle.load(f)
f.close()
from depthmap import get_distance
distances = get_distance(depths, .2, 1.0)
box_distances = get_distance(box_depths, .2, 1.0)
distances[distances > .99] = None
box_distances[box_distances > .99] = None
from mpl_toolkits.mplot3d import axes3d, Axes3D
X = np.arange(0, depths.shape[1])
Y = np.arange(0, depths.shape[2])
X, Y = np.meshgrid(X, Y)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
ax.plot_wireframe(X, Y, distances[205,:,:], color='b')
ax.plot_wireframe(X, Y, box_distances[205,:,:], color='r')
plt.show()
def load_depth_image(directory, object, index):
imfile = directory + object + str(index) + '.png'
image = scipy.ndimage.imread(imfile, flatten=True)
def get_pos_rot(objects, gripper_pos, gripper_orient, obj):
"""
Get positions and rotation matrices for a given object, from a parameter list for
all objects.
"""
pos = []
rot = []
for i in range(len(objects)):
if objects[i] == obj:
pos.append(gripper_pos[i])
rot.append(rot_matrix(gripper_orient[i][0], gripper_orient[i][1], gripper_orient[i][2]))
return np.array(pos), np.array(rot)
def process_directory(obj_dir, image_dir, support=False):
from os import listdir
from os.path import isfile, join
import time
objects, gripper_pos, gripper_orient, labels = load_all_params('../../grasp-conv/data/output_data.csv')
bottom = 0 if support else 0.2
for f in listdir(obj_dir):
obj_filename = join(obj_dir, f)
if isfile(obj_filename) and f.endswith('.obj'):
print('Processing ' + f)
start_time = time.time()
pos, rot = get_pos_rot(objects, gripper_pos, gripper_orient, f)
make_depth_images(f[:-4], pos, rot, obj_dir, image_dir, bottom=bottom, support=support)
print(' ' + str(time.time()-start_time) + 's')
def calculate_grasp_metrics_for_directory(image_dir, im_width=80,
camera_offset=.45, near_clip=.25, far_clip=.8):
from os import listdir
from os.path import isfile, join
import time
from heuristic import finger_path_template
from heuristic import calculate_grip_metrics
template = finger_path_template(45.*np.pi/180., im_width, camera_offset)
all_intersections = []
all_qualities = []
all_files = []
for f in listdir(image_dir):
image_filename = join(image_dir, f)
if isfile(image_filename) and f.endswith('.png'):
# print('Processing ' + image_filename)
image = scipy.misc.imread(image_filename)
rescaled_distance = image / 255.0
distance = rescaled_distance*(far_clip-camera_offset)+camera_offset
# from mpl_toolkits.mplot3d import axes3d, Axes3D
# X = np.arange(0, im_width)
# Y = np.arange(0, im_width)
# X, Y = np.meshgrid(X, Y)
# fig = plt.figure()
# distance[distance > camera_offset + .3] = None
# template[template < camera_offset] = None
# ax = fig.add_subplot(1,1,1,projection='3d')
# ax.plot_wireframe(X, Y, distance)
# ax.plot_wireframe(X, Y, template, color='r')
# ax.set_xlabel('x')
# plt.show()
intersections, qualities = calculate_grip_metrics(distance, template)
# print(intersections)
# print(qualities)
all_intersections.append(intersections)
all_qualities.append(qualities)
all_files.append(f)
return all_intersections, all_qualities, all_files
def calculate_grasp_metric_maps_for_directory(image_dir, dest_dir, im_width=80,
camera_offset=.45, near_clip=.25, far_clip=.8):
from os import listdir
from os.path import isfile, join
from heuristic import finger_path_template
finger_path = finger_path_template(45.*np.pi/180., im_width, camera_offset)
for f in listdir(image_dir):
image_filename = join(image_dir, f)
if isfile(image_filename) and f.endswith('.png'):
print('Processing ' + image_filename)
image = scipy.misc.imread(image_filename)
rescaled_distance = image / 255.0
distance = rescaled_distance*(far_clip-camera_offset)+camera_offset
mm = calculate_metric_map(distance, finger_path, 1)
imfile = dest_dir + f[:-4] + '-map' + '.png'
Image.fromarray((255.0*mm).astype('uint8')).save(imfile)
def calculate_overlap_for_directory(image_dir, dest_dir, im_width=80,
camera_offset=.45, far_clip=.8):
from os import listdir
from os.path import isfile, join
from heuristic import finger_path_template
finger_path = finger_path_template(45.*np.pi/180., im_width, camera_offset)
c = 0
for f in listdir(image_dir):
image_filename = join(image_dir, f)
if isfile(image_filename) and f.endswith('.png'):
if c % 1000 == 0:
print('Processing ' + image_filename)
c += 1
image = scipy.misc.imread(image_filename)
rescaled_distance = image / 255.0
distance = rescaled_distance*(far_clip-camera_offset)+camera_offset
overlap = np.maximum(0, finger_path - distance)
imfile = dest_dir + f[:-4] + '-overlap' + '.png'
# we divide by 15.4cm because it's the max overlap due to gripper geometry
Image.fromarray((255.0/.154*overlap).astype('uint8')).save(imfile)
def compress_images(directory, extension, name='zip'):
"""
We need this to transfer data to server.
"""
from os import listdir
from os.path import isfile, join
from zipfile import ZipFile
n_per_zip = 50000
# with ZipFile('zip-all.zip', 'w') as zf:
# for f in listdir(directory):
# image_filename = join(directory, f)
# if isfile(image_filename) and f.endswith(extension):
# zf.write(image_filename)
zip_index = 0
file_index = 0
for f in listdir(directory):
image_filename = join(directory, f)
if isfile(image_filename) and f.endswith(extension):
if file_index == 0:
zf = ZipFile(name + str(zip_index) + '.zip', 'w')
zf.write(image_filename)
file_index += 1
if file_index == n_per_zip:
print('writing file ' + str(zip_index))
file_index = 0
zf.close()
zip_index += 1
zf.close()
if __name__ == '__main__':
# save_bowl_and_box_depths()
# plot_bowl_and_box_distance_example()
# compress_images('../../grasp-conv/data/support_depths/', '.png')
# compress_images('../../grasp-conv/data/obj_depths/', '.png')
# compress_images('../../grasp-conv/data/obj_mm/', '.png')
# compress_images('../../grasp-conv/data/support_overlap/', '.png', name='support-overlap')
# compress_images('../../grasp-conv/data/obj_overlap/', '.png', name='obj-overlap')
compress_images('/Volumes/TrainingData/grasp-conv/data/eye-perspectives', '.png', name='eye-perspectives')
# calculate_grasp_metric_maps_for_directory('../../grasp-conv/data/obj_depths/', '../../grasp-conv/data/obj_mm/')
# image = scipy.misc.imread('../../grasp-conv/data/obj_mm/104_toaster_final-18-Dec-2015-13-56-59-0-map.png')
# mm = image / 255.0
# print(np.min(mm))
# print(np.max(mm))
# objects, gripper_pos, gripper_orient, labels = load_all_params('../../grasp-conv/data/output_data.csv')
# obj_dir = '../../grasp-conv/data/obj_files/'
# process_directory(obj_dir, '../../grasp-conv/data/obj_depths/')
# # process_directory(obj_dir, '../../grasp-conv/data/support_depths/', support=True)
#
# # intersections, qualities, files = calculate_grasp_metrics_for_directory('../../grasp-conv/data/support_depths/')
# intersections, qualities, files = calculate_grasp_metrics_for_directory('../../grasp-conv/data/obj_depths/')
# f = file('../data/metrics-objects.pkl', 'wb')
# cPickle.dump((intersections, qualities, files), f)
# f.close()
# calculate_overlap_for_directory('../../grasp-conv/data/obj_depths/', '../../grasp-conv/data/obj_overlap/')
# calculate_overlap_for_directory('../../grasp-conv/data/support_depths/', '../../grasp-conv/data/support_overlap/')
# f = file('metrics.pkl', 'rb')
# intersections, qualities = cPickle.load(f)
# f.close()
# print(intersections)
# print(qualities)
# from mpl_toolkits.mplot3d import axes3d, Axes3D
# X = np.arange(0, 80)
# Y = np.arange(0, 80)
# X, Y = np.meshgrid(X, Y)
# fig = plt.figure()
# ax = fig.add_subplot(1,1,1,projection='3d')
# ax.plot_wireframe(X, Y, foo)
# ax.set_xlabel('x')
# plt.show()
| {
"repo_name": "bptripp/grasp-convnet",
"path": "py/data.py",
"copies": "1",
"size": "26522",
"license": "mit",
"hash": 8336879002755659000,
"line_mean": 36.4076163611,
"line_max": 132,
"alpha_frac": 0.5748058216,
"autogenerated": false,
"ratio": 2.9613666815542654,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9028794386960786,
"avg_score": 0.0014756232386961279,
"num_lines": 709
} |
__author__ = 'bptripp'
import time
import numpy as np
import matplotlib
matplotlib.rcParams['xtick.labelsize'] = 18
matplotlib.rcParams['ytick.labelsize'] = 18
import matplotlib.pyplot as plt
from cnn_stimuli import get_image_file_list
from alexnet import preprocess, load_net, load_vgg
scales = np.logspace(np.log10(.05), np.log10(1.2), 45) #copied from cnn_stimuli (bad idea!)
model = load_net(weights_path='../weights/alexnet_weights.h5')
use_vgg = False
# model = load_vgg(weights_path='../weights/vgg16_weights.h5')
# use_vgg=True
# if use_vgg:
# model = load_vgg(weights_path='../weights/vgg16_weights.h5', remove_level=remove_levels[i])
# else:
# model = load_net(weights_path='../weights/alexnet_weights.h5', remove_level=remove_levels[i])
def correlations(out):
cc = np.corrcoef(out.T)
result = []
for i in range(cc.shape[0]):
for j in range(i+1,cc.shape[1]):
result.append(cc[i][j])
return result
def invariant(out):
#dims: object, size
# return np.mean([cc[0,1], cc[0,2], cc[1,2]]) > .7
# return np.mean([cc[0,1], cc[0,2], cc[1,2]]) > .5
return np.mean(correlations(out)) > .75
def clear_preference(out):
# one size is clearly preferred in that it elicits a stronger response for each shape
max_ind = np.argmax(out, axis=1)
# print(max_ind)
return np.max(np.abs(np.diff(max_ind))) == 0
def bandwidth(scales, responses):
peak_ind = np.argmax(responses)
peak = responses[peak_ind]
top = peak_ind
for i in range(peak_ind, len(responses)):
if responses[i] > peak/2:
top = i
else:
break
bottom = peak_ind
for i in range(peak_ind, -1, -1):
if responses[i] > peak/2:
bottom = i
else:
break
result = np.log2(scales[top] / scales[bottom])
# print('bandwidth')
# print(peak_ind)
# print(bottom)
# print(top)
# print(result)
return result
if False:
# plot Schwartz et al. (1983) example
deg13 = np.loadtxt(open('../data/deg13.csv', 'rb'), delimiter=',')
deg28 = np.loadtxt(open('../data/deg28.csv', 'rb'), delimiter=',')
deg50 = np.loadtxt(open('../data/deg50.csv', 'rb'), delimiter=',')
o = np.zeros((6,3))
o[:,0] = deg13[:,1]
o[:,1] = deg28[:,1]
o[:,2] = deg50[:,1]
plt.figure(figsize=(4,3.5))
plt.plot(range(1,7), o)
plt.tight_layout()
plt.xlabel('Stimulus #', fontsize=18)
plt.ylabel('Response (spikes/s)', fontsize=18)
plt.tight_layout()
plt.savefig('../figures/size-schwartz-example.eps')
plt.show()
# plt.semilogx([2, 4, 8, 16, 32, 64], o)
print('Schwartz correlation ' + str(np.mean(correlations(o))))
if False:
# plot mean correlations and fraction with clear preference
layers = [-2, -1, 0]
plt.figure(figsize=(4,3.5))
alexnet_correlations = [0.495586845637, 0.530755560076, 0.721706983642]
vgg_correlations = [0.444102093071, 0.524417339524, 0.613046758844]
schwartz_correlation = 0.958892832321
plt.plot(layers, alexnet_correlations)
plt.plot(layers, vgg_correlations)
plt.plot(layers, schwartz_correlation*np.array([1, 1, 1]), 'k--')
plt.xlabel('Distance from output (layers)', fontsize=16)
plt.ylabel('Mean correlation', fontsize=16)
plt.xticks([-2,-1,0])
plt.ylim([0, 1])
plt.tight_layout()
plt.savefig('../figures/size-correlations.eps')
plt.show()
plt.figure(figsize=(4,3.5))
alexnet_fractions = [0.03125, 0.046875, 0.03125]
vgg_fractions = [0.0625, 0.046875, 0.015625]
plt.plot(layers, alexnet_fractions)
plt.plot(layers, vgg_fractions)
plt.xlabel('Distance from output (layers)', fontsize=16)
plt.ylabel('Fraction with preference', fontsize=16)
plt.xticks([-2,-1,0])
plt.ylim([0, 1])
plt.tight_layout()
plt.savefig('../figures/size-preferences.eps')
plt.show()
if True:
use_vgg = True
remove_level = 0
if use_vgg:
model = load_vgg(weights_path='../weights/vgg16_weights.h5', remove_level=remove_level)
else:
model = load_net(weights_path='../weights/alexnet_weights.h5', remove_level=remove_level)
out = []
stimuli = ['f1', 'f2', 'f3', 'f4', 'f5', 'f6']
for stimulus in stimuli:
image_files = get_image_file_list('./images/scales/' + stimulus, 'png', with_path=True)
im = preprocess(image_files, use_vgg=use_vgg)
out.append(model.predict(im))
out = np.array(out)
print(out.shape)
# plot invariance with Schwartz stimuli
i = 0
c = 0
n_invariant = 0
n_clear = 0
mean_correlations = []
while c < 64:
plt.subplot(8,8,c+1)
o = out[:,:,i]
# if np.max(o) > .1:
if np.max(o) > 1:
plt.plot(o)
yl = plt.gca().get_ylim()
if invariant(o):
n_invariant = n_invariant + 1
plt.text(4.3, yl[0] + (yl[1]-yl[0])*.8, 'c', fontsize=14)
if clear_preference(o):
n_clear = n_clear + 1
plt.text(.1, yl[0] + (yl[1]-yl[0])*.8, 'p', fontsize=14)
mean_correlations.append(np.mean(correlations(o)))
plt.xticks([])
plt.yticks([])
c = c + 1
i = i + 1
print(mean_correlations)
print('fraction with preference ' + str(float(n_clear)/64.))
print('mean correlation ' + str(np.nanmean(mean_correlations)))
plt.tight_layout()
net = 'vgg16' if use_vgg else 'alexnet'
plt.savefig('../figures/size-invariance-' + net + '-' + str(remove_level) + '.eps')
plt.show()
if False: #plot invariance with naturalistic stimuli
size_ind = (25,30,34) # roughly matched with Schwartz et al. (see cnn_stimuli)
i = 0
c = 0
n_invariant = 0
# for i in range(9):
while c < 64:
plt.subplot(8,8,c+1)
o = out[:,size_ind,i]
if np.max(o) > .1:
plt.plot(o)
# print(out[:,size_ind,i])
# print(invariant(o))
if invariant(o):
n_invariant = n_invariant + 1
plt.text(1.8, np.max(o)*.7, '*', fontsize=16)
plt.xticks([])
plt.yticks([])
# plt.title(str(i) + ' ' + str(invariant(o)))
c = c + 1
i = i + 1
print(n_invariant)
plt.tight_layout()
plt.savefig('../figures/size-invariance.eps')
plt.show()
if False: # plot example tuning curves
# image_files = get_image_file_list('./images/scales/banana', 'png', with_path=True)
# image_files = get_image_file_list('./images/scales/shoe', 'png', with_path=True)
image_files = get_image_file_list('./images/scales/corolla', 'png', with_path=True)
im = preprocess(image_files, use_vgg=use_vgg)
object_responses = model.predict(im)
# object_responses = np.squeeze(out[0,:,:])
maxima = np.max(object_responses, axis=0)
n = 50
ind = (-maxima).argsort()[:n]
plt.plot(scales, object_responses[:,ind])
prefs = np.zeros(n)
for i in range(n):
bandwidth(scales, object_responses[:,ind[i]])
prefs[i] = scales[np.argmax(object_responses[:,ind[i]])]
plt.show()
plt.hist(prefs)
plt.show()
def get_max_indices(object_responses, n=500):
maxima = np.max(object_responses, axis=0)
return (-maxima).argsort()[:n]
def get_bandwidth(object_responses, ind):
n = len(ind)
bandwidths = np.zeros(n)
prefs = np.zeros(n)
for i in range(n):
size_tuning_curve = object_responses[:,ind[i]]
bandwidths[i] = bandwidth(scales, size_tuning_curve)
prefs[i] = scales[np.argmax(size_tuning_curve)]
return bandwidths, prefs
if False:
data = np.loadtxt(open('../data/ito.csv', 'rb'), delimiter=',')
bandwidths = np.squeeze(data[:,1])
bandwidths[bandwidths>3.95] = 4.01 #these are on the line
print(bandwidths)
fs = 18
hist_edges = [x * .5 for x in range(13)]
plt.figure(figsize=(3,3))
plt.hist(bandwidths[bandwidths<4], hist_edges)
plt.hist(bandwidths[bandwidths>=4], hist_edges, color=[1,0,0])
plt.xlabel('Size BW (Octaves)', fontsize=fs)
plt.ylabel('Frequency', fontsize=fs)
plt.tight_layout()
plt.savefig('../figures/bandwidth-ito.eps')
plt.show()
if False: # plot histograms of bandwidth and preferred size
out = []
image_files = get_image_file_list('./images/scales/banana', 'png', with_path=True)
im = preprocess(image_files, use_vgg=use_vgg)
out.append(model.predict(im))
image_files = get_image_file_list('./images/scales/shoe', 'png', with_path=True)
im = preprocess(image_files, use_vgg=use_vgg)
out.append(model.predict(im))
image_files = get_image_file_list('./images/scales/corolla', 'png', with_path=True)
im = preprocess(image_files, use_vgg=use_vgg)
out.append(model.predict(im))
out = np.array(out)
fs = 18
hist_edges = [x * .5 for x in range(13)]
plt.figure(figsize=(3,3))
n = 200
bandwidths = np.zeros((3*n))
for i in range(3):
# plt.subplot(1,3,i+1)
object_responses = np.squeeze(out[i,:,:])
ind = get_max_indices(object_responses, n=200)
bandwidths[n*i:n*(i+1)], prefs = get_bandwidth(object_responses, ind)
plt.hist(bandwidths, hist_edges)
plt.xlabel('Size BW (Octaves)', fontsize=fs)
plt.ylabel('Frequency', fontsize=fs)
plt.tight_layout()
if use_vgg:
plt.savefig('../figures/bandwidth-vgg16.eps')
else:
plt.savefig('../figures/bandwidth-alexnet.eps')
plt.show()
# print('preferences mean: ' + str(np.mean(prefs)))
# print('preferences min: ' + str(np.min(prefs)))
# print('preferences max: ' + str(np.max(prefs)))
# print('bandwidth mean: ' + str(np.mean(bandwidths)))
# print('bandwidth max: ' + str(np.max(bandwidths)))
# plt.figure(figsize=(10,3))
# plt.subplot(1,2,1)
# plt.hist(prefs, 8)
# plt.xlabel('Preferred Scale', fontsize=fs)
# plt.ylabel('Frequency', fontsize=fs)
# plt.subplot(1,2,2)
# plt.hist(bandwidths, 10)
# plt.xlabel('Size BW (Octaves)', fontsize=fs)
# plt.ylabel('Frequency', fontsize=fs)
# plt.tight_layout()
# plt.savefig('../figures/bandwidth.eps')
# plt.show()
| {
"repo_name": "bptripp/it-cnn",
"path": "tuning/size.py",
"copies": "1",
"size": "10236",
"license": "mit",
"hash": -2986005213834400300,
"line_mean": 30.4953846154,
"line_max": 99,
"alpha_frac": 0.5980851895,
"autogenerated": false,
"ratio": 3.023929098966027,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.41220142884660266,
"avg_score": null,
"num_lines": null
} |
__author__ = 'bptripp'
# Just like perspective_model, but with ray-based metrics instead of depth map-based metrics as targets.
from os import listdir
from os.path import isfile, join
import cPickle
import numpy as np
import scipy
from keras.models import Sequential
from keras.layers.core import Dense, Flatten, Dropout, Activation
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.optimizers import Adam
from keras.models import model_from_json
from keras.regularizers import activity_l2
num_outputs = 25
def get_model():
model = Sequential()
model.add(Convolution2D(64, 7, 7, input_shape=(1,80,80), init='glorot_normal', border_mode='same', activity_regularizer=activity_l2(0.0000001)))
model.add(Activation('relu'))
model.add(Convolution2D(64, 3, 3, init='glorot_normal', border_mode='same', activity_regularizer=activity_l2(0.0000001)))
model.add(Activation('relu'))
model.add(Convolution2D(64, 3, 3, init='glorot_normal', border_mode='same', activity_regularizer=activity_l2(0.0000001)))
model.add(Activation('relu'))
model.add(MaxPooling2D((2,2)))
model.add(Flatten())
model.add(Dense(256, activity_regularizer=activity_l2(0.0000001)))
model.add(Activation('relu'))
model.add(Dropout(.5))
model.add(Dense(1024, activity_regularizer=activity_l2(0.0000001)))
model.add(Activation('relu'))
model.add(Dropout(.5))
model.add(Dense(num_outputs))
adam = Adam(lr=0.000001, beta_1=0.9, beta_2=0.999, epsilon=1e-08)
model.compile(loss='mse', optimizer=adam)
return model
def load_model(weights_file='p2-model-weights.h5'):
model = model_from_json(open('p2-model-architecture-25-reg.json').read())
model.load_weights(weights_file)
adam = Adam(lr=0.000001, beta_1=0.9, beta_2=0.999, epsilon=1e-08)
model.compile(loss='mse', optimizer=adam)
return model
def load_data():
import csv
objects = []
with open('../data/eye-perspectives-objects.csv') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
objects.append(row[0])
image_filenames = []
for i in range(len(objects)):
case = i % 200
target = case / 20
eye = case % 20
fn = objects[i][:-4] + '-' + str(target) + '-' + str(eye) + '.png'
image_filenames.append(fn)
neuron_metrics = []
with open('../data/ray-metrics.csv') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
neuron_metrics.append(row)
neuron_metrics = np.array(neuron_metrics)
return image_filenames, neuron_metrics[:,:num_outputs]
def get_input(image_dir, image_file):
image = scipy.misc.imread(join(image_dir, image_file))
return np.array(image / 255.0)
def get_XY(image_dir, image_filenames, neuron_metrics, indices):
X = []
Y = []
for ind in indices:
X.append(get_input(image_dir, image_filenames[ind])[np.newaxis,:])
Y.append(neuron_metrics[ind])
return np.array(X), np.array(Y)
def train_model(model, image_dir, train_indices, valid_indices):
image_filenames, neuron_metrics = load_data()
print(len(image_filenames))
X_valid, Y_valid = get_XY(image_dir, image_filenames, neuron_metrics, valid_indices)
def generate_XY():
while 1:
batch_X = []
batch_Y = []
for i in range(32):
ind = train_indices[np.random.randint(len(train_indices))]
X = get_input(image_dir, image_filenames[ind])
Y = neuron_metrics[ind]
batch_X.append(X[np.newaxis,:])
batch_Y.append(Y)
yield (np.array(batch_X), np.array(batch_Y))
for i in range(11,16):
h = model.fit_generator(generate_XY(),
samples_per_epoch=8192, nb_epoch=100,
validation_data=(X_valid, Y_valid))
with file('p2-history-25-reg-' + str(i) + '.pkl', 'wb') as f:
cPickle.dump(h.history, f)
json_string = model.to_json()
open('p2-model-architecture-25-reg.json', 'w').write(json_string)
model.save_weights('p2-model-weights-25-reg-' + str(i) + '.h5', overwrite=True)
def predict(model, image_dir, indices):
image_filenames, neuron_metrics = load_data()
X, Y = get_XY(image_dir, image_filenames, neuron_metrics, indices)
return Y, model.predict(X, batch_size=32, verbose=0)
if __name__ == '__main__':
# image_filenames, neuron_metrics = load_data()
valid_indices = np.arange(0, 50000, 100)
s = set(valid_indices)
train_indices = [x for x in range(70000) if x not in s]
#model = get_model()
model = load_model(weights_file='p2-model-weights-25-reg-10.h5')
train_model(model,
'../../grasp-conv/data/eye-perspectives',
train_indices,
valid_indices)
#model = load_model(weights_file='p2-model-weights-big-reg-12.h5')
#targets, predictions = predict(model,
# '../../grasp-conv/data/eye-perspectives',
# valid_indices)
#with open('perspective-predictions-big-reg-12.pkl', 'wb') as f:
# cPickle.dump((targets, predictions), f)
| {
"repo_name": "bptripp/grasp-convnet",
"path": "py/perspective_model2.py",
"copies": "1",
"size": "5197",
"license": "mit",
"hash": -7916265495153750000,
"line_mean": 33.1907894737,
"line_max": 148,
"alpha_frac": 0.6313257649,
"autogenerated": false,
"ratio": 3.268553459119497,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4399879224019497,
"avg_score": null,
"num_lines": null
} |
__author__ = 'bptripp'
"""
Bertsekas' Auction Algorithm. This is a nearly line-by-line port of the Matlab implementation by Florian Bernard:
http://www.mathworks.com/matlabcentral/fileexchange/48448-fast-linear-assignment-problem-using-auction-algorithm
And this is a nice introduction to the algorithm:
Bertsekas, D. P. (1990). The Auction Algorithm for Assignment and Other Network Flow Problems: A Tutorial.
Interfaces, 20(4)
Bernard's Matlab code is distributed under the BSD License, as follows:
Copyright (c) 2014, Florian Bernard
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
This code is also distributed under the BSD License, Copyright (2015) Bryan Tripp.
Note that Bertsekas's Fortran code is also online: http://www.mit.edu/~dimitrib/auction.txt
"""
import time
import numpy as np
def auction(A, epsilon=None, epsilonDecreaseFactor=None):
"""
Parameters
----------
:param A:
:param epsilon:
:param epsilonDecreaseFactor:
Returns
-------
:return assignments: best assignment per row of A
:return prices:
"""
N = A.shape[0]
prices = np.ones(N)
A = A * N+1
# heuristic for setting epsilon
if epsilon is None:
# epsilon = np.max(np.abs(A[:])) / 25.0 #this sometimes make us skip the loop
epsilon = np.maximum(1, np.max(np.abs(A[:])) / 15.0)
if epsilonDecreaseFactor is None:
epsilonDecreaseFactor = 0.2
while epsilon >= 1:
# The outer loop performs epsilon-scaling in order to speed up execution
# time. In particular, an updated prices array is computed in each
# round, which speeds up further rounds with lower values of epsilon.
assignments = np.empty(N)
assignments[:] = np.NAN
while np.any(np.isnan(assignments)):
# Forward-Auction Algorithm -- Bidding Phase
# find unassigned indices
unassignedIdx, = np.nonzero(np.isnan(assignments))
nUnassigned = len(unassignedIdx)
# find best and second best objects
AijMinusPj = A[unassignedIdx, :] - prices
viIdx = np.argmax(AijMinusPj, axis=1)
for i in range(nUnassigned):
AijMinusPj[i][viIdx[i]] = -np.Inf
# print(AijMinusPj)
wi = np.max(AijMinusPj, axis=1)
# compute bids
bids = np.empty(nUnassigned)
bids[:] = np.NAN
for i in range(nUnassigned):
bids[i] = A[unassignedIdx[i], viIdx[i]] - wi[i] + epsilon
# Assignment Phase
objectsThatHaveBeenBiddedFor = np.unique(viIdx)
for uniqueObjIdx in range(len(objectsThatHaveBeenBiddedFor)):
currObject = objectsThatHaveBeenBiddedFor[uniqueObjIdx]
personssWhoGaveBidsForJ = np.nonzero(viIdx==currObject)
b = bids[personssWhoGaveBidsForJ]
idx = np.argmax(b)
prices[currObject] = b[idx]
personWithHighestBid = unassignedIdx[personssWhoGaveBidsForJ[0][idx]]
# remove previous assignment and store new assignment (person with highest bid)
assignments[assignments==currObject] = np.NaN
assignments[personWithHighestBid] = currObject
# print(assignments)
epsilon = epsilon * epsilonDecreaseFactor # refine epsilon
return assignments, prices
if __name__ == '__main__':
A = np.array([[5, 9, 2], [10, 3, 2], [8, 7, 4]])
print(A)
start_time = time.time()
assignments, prices = auction(A)
print(assignments)
print('auction time: ' + str(time.time() - start_time))
| {
"repo_name": "bptripp/it-cnn",
"path": "auction.py",
"copies": "1",
"size": "4988",
"license": "mit",
"hash": 1182420263333599700,
"line_mean": 36.223880597,
"line_max": 116,
"alpha_frac": 0.6595829992,
"autogenerated": false,
"ratio": 3.996794871794872,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0014786096196599246,
"num_lines": 134
} |
__author__ = 'bptripp'
"""
The input to this network isn't depth maps, but rather a group of hand-engineered features.
"""
import csv
import numpy as np
from os.path import join
import scipy
import cPickle
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import Adam
from data import load_all_params
model = Sequential()
model.add(Dense(256, input_shape=[25]))
model.add(Activation('relu'))
model.add(Dropout(.25))
model.add(Dense(256))
model.add(Activation('relu'))
model.add(Dropout(.25))
model.add(Dense(1))
model.add(Activation('sigmoid'))
adam = Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-08)
model.compile(loss='binary_crossentropy', optimizer=adam)
labels = []
features = []
with open('correlates.csv', 'rb') as csvfile:
r = csv.reader(csvfile, delimiter=',')
for row in r:
labels.append(row[0])
features.append(row[1:])
labels = np.array(labels).astype(float)
features = np.array(features).astype(float)
# normalize features ...
for i in range(features.shape[1]):
features[:,i] = features[:,i] - np.mean(features[:,i])
features[:,i] = features[:,i] / np.std(features[:,i])
n = len(labels)
validation_indices = np.random.randint(0, n, 500)
s = set(validation_indices)
train_indices = [x for x in range(n) if x not in s]
Y_valid = labels[validation_indices,np.newaxis]
X_valid = features[validation_indices,:]
Y_train = labels[train_indices,np.newaxis]
X_train = features[train_indices,:]
# print(Y_valid.shape)
# print(X_valid.shape)
# print(Y_train.shape)
# print(X_train.shape)
h = model.fit(X_train, Y_train, nb_epoch=500, validation_data=(X_valid, Y_valid))
| {
"repo_name": "bptripp/grasp-convnet",
"path": "py/correlates_model.py",
"copies": "1",
"size": "1688",
"license": "mit",
"hash": 6371515681995578000,
"line_mean": 26.6721311475,
"line_max": 91,
"alpha_frac": 0.7049763033,
"autogenerated": false,
"ratio": 2.9770723104056436,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9163860625861889,
"avg_score": 0.0036375975687508604,
"num_lines": 61
} |
__author__ = 'bptripp'
"""
The input to this network isn't depth maps, but rather depth of overlap between
object / support and gripper finger trajectory.
"""
import numpy as np
from os.path import join
import scipy
import cPickle
from keras.models import Sequential
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.optimizers import Adam
from data import load_all_params
model = Sequential()
model.add(Convolution2D(64, 7, 7, input_shape=(2,80,16), init='glorot_normal', border_mode='same'))
model.add(Activation('relu'))
model.add(Convolution2D(64, 3, 3, init='glorot_normal', border_mode='same'))
model.add(Activation('relu'))
model.add(Dropout(.5))
model.add(Convolution2D(64, 3, 3, init='glorot_normal', border_mode='same'))
model.add(Activation('relu'))
model.add(Dropout(.5))
model.add(Flatten())
model.add(Dense(1024))
model.add(Activation('relu'))
model.add(Dropout(.5))
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))
adam = Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-08)
model.compile(loss='binary_crossentropy', optimizer=adam)
objects, gripper_pos, gripper_orient, labels = load_all_params('../../grasp-conv/data/output_data.csv')
seq_nums = np.arange(len(objects)) % 1000 #exactly 1000 per object in above file (dated March 18)
labels = np.array(labels)[:,np.newaxis]
n = len(objects)
validation_indices = np.random.randint(0, n, 5000) #TODO: generalize across objects
s = set(validation_indices)
train_indices = [x for x in range(n) if x not in s]
f = file('o-valid-ind.pkl', 'wb')
cPickle.dump(validation_indices, f)
f.close()
def get_input(object, seq_num):
image_file = object[:-4] + '-' + str(seq_num) + '-overlap.png'
X = []
image_dir = '../../grasp-conv/data/obj_overlap/'
image = scipy.misc.imread(join(image_dir, image_file))
X.append(image[:,32:48] / 255.0)
image_dir = '../../grasp-conv/data/support_overlap/'
image = scipy.misc.imread(join(image_dir, image_file))
X.append(image[:,32:48] / 255.0)
return np.array(X)
Y_valid = labels[validation_indices,:]
X_valid = []
for ind in validation_indices:
X_valid.append(get_input(objects[ind], seq_nums[ind]))
X_valid = np.array(X_valid)
def generate_XY():
while 1:
batch_X = []
batch_Y = []
for i in range(32):
ind = train_indices[np.random.randint(len(train_indices))]
Y = np.zeros((1))
Y[0] = labels[ind,0]
X = get_input(objects[ind], seq_nums[ind])
#X = X[np.newaxis,:,:,:]
batch_X.append(X)
batch_Y.append(Y)
yield (np.array(batch_X), np.array(batch_Y))
# X = get_input(objects[0], 0)
# import matplotlib.pyplot as plt
# fig = plt.figure(figsize=(10,5))
# ax = plt.subplot(1,2,1)
# plt.imshow(X[0,:,:])
# ax = plt.subplot(1,2,2)
# plt.imshow(X[1,:,:])
# plt.show()
h = model.fit_generator(generate_XY(),
samples_per_epoch=32768, nb_epoch=250,
validation_data=(X_valid, Y_valid))
f = file('o-history.pkl', 'wb')
cPickle.dump(h.history, f)
f.close()
json_string = model.to_json()
open('o-model-architecture.json', 'w').write(json_string)
model.save_weights('o-model-weights.h5', overwrite=True)
| {
"repo_name": "bptripp/grasp-convnet",
"path": "py/overlap_model.py",
"copies": "1",
"size": "3344",
"license": "mit",
"hash": 1837334114612783000,
"line_mean": 28.8571428571,
"line_max": 103,
"alpha_frac": 0.6662679426,
"autogenerated": false,
"ratio": 2.8902333621434746,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8996346266073552,
"avg_score": 0.012031007733984416,
"num_lines": 112
} |
__author__ = 'bptripp'
# Testing responses of pre-trained AlexNet for comparison with IT
from keras.optimizers import SGD
from keras.layers import Flatten
import keras
import numpy as np
from convnetskeras.convnets import preprocess_image_batch, convnet
def load_net(remove_last_layer=True, weights_path='weights/alexnet_weights.h5', units_to_keep=None, remove_level=1):
sgd = SGD(lr=0.00001, decay=1e-6, momentum=0.9, nesterov=True)
model = convnet('alexnet', weights_path=weights_path, heatmap=False)
if remove_last_layer:
pop(model) #activation
if remove_level > 0:
pop(model) #dense
pop(model) #dropout
if remove_level > 1:
pop(model) #dense
pop(model) #dropout
# https://github.com/fchollet/keras/issues/2640
# although it looks like this is done correctly already
model.layers[-1].outbound_nodes = []
model.outputs = [model.layers[-1].output]
# this code is from Container.__init__
model.internal_output_shapes = [x._keras_shape for x in model.outputs]
# for layer in model.layers:
# print(layer)
model.compile(optimizer=sgd, loss='mse')
return model
def load_vgg(remove_last_layer=True, weights_path='weights/vgg16_weights.h5', units_to_keep=None, remove_level=1):
sgd = SGD(lr=0.00001, decay=1e-6, momentum=0.9, nesterov=True)
model = convnet('vgg_16', weights_path=weights_path, heatmap=False)
if remove_last_layer:
pop(model) #activation
if remove_level > 0:
pop(model) #dense
pop(model) #dropout
if remove_level > 1:
pop(model) #dense
pop(model) #dropout
if remove_level > 2:
pop(model) #dense
pop(model) #flatten
model.add(Flatten(name='flatten'))
if remove_level > 3:
pop(model) #flatten added above
pop(model) #maxpool
pop(model) #conv
pop(model) #zeropad
pop(model) #conv
pop(model) #zeropad
pop(model) #conv
pop(model) #zeropad
model.add(Flatten(name='flatten'))
if remove_level > 4:
pop(model) #flatten added above
pop(model) #maxpool
pop(model) #conv
pop(model) #zeropad
pop(model) #conv
pop(model) #zeropad
pop(model) #conv
pop(model) #zeropad
model.add(Flatten(name='flatten'))
# https://github.com/fchollet/keras/issues/2640
# although it looks like this is done correctly already
model.layers[-1].outbound_nodes = []
model.outputs = [model.layers[-1].output]
# this code is from Container.__init__
model.internal_output_shapes = [x._keras_shape for x in model.outputs]
# for layer in model.layers:
# print(layer)
model.compile(optimizer=sgd, loss='mse')
return model
# adapted from https://github.com/fchollet/keras/issues/2371
def pop(model):
'''Removes a layer instance on top of the layer stack.
'''
if not model.outputs:
raise Exception('Sequential model cannot be popped: model is empty.')
else:
model.layers.pop()
if not model.layers:
model.outputs = []
model.inbound_nodes = []
model.outbound_nodes = []
else:
model.layers[-1].outbound_nodes = []
model.outputs = [model.layers[-1].output]
model.built = False
def preprocess(image_files, use_vgg=False):
"""
:param image_files:
:return: array of image data with default params
"""
if use_vgg:
return preprocess_image_batch(image_files, img_size=(256,256), crop_size=(224,224), color_mode="bgr")
else:
return preprocess_image_batch(image_files, img_size=(256,256), crop_size=(227,227), color_mode="rgb")
# foo = np.moveaxis(foo, 1, 3)
# print(foo.shape)
if __name__ == '__main__':
load_net(weights_path='./weights/alexnet_weights.h5', units_to_keep=100)
| {
"repo_name": "bptripp/it-cnn",
"path": "alexnet.py",
"copies": "1",
"size": "4129",
"license": "mit",
"hash": 5789811955364366000,
"line_mean": 29.3602941176,
"line_max": 116,
"alpha_frac": 0.5957859046,
"autogenerated": false,
"ratio": 3.606113537117904,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9630880579810598,
"avg_score": 0.014203772381461288,
"num_lines": 136
} |
__author__ = 'brad'
import pyaudio
import wave
import cStringIO
class SoundStream():
def __init__(self, pya, address):
if address is not None:
self.file = wave.open(str(address), 'rb')
self.pya = pya
self.stream = None
self.address = address
self.chunk = 1024
self.channels = 2
self.complete = False
def callback(self, in_data, frame_count, time_info, status):
data = ''
data = self.file.readframes(frame_count)
if data == '':
data = chr(0)*self.file.getnchannels()*self.file.getsampwidth()*frame_count
if len(data) < self.file.getnchannels()*self.file.getsampwidth()*frame_count:
length = self.file.getnchannels()*self.file.getsampwidth()*frame_count - len(data)
data += chr(0) * length
return data, pyaudio.paContinue
def play(self, sound_file=None):
if sound_file is not None:
self.address = sound_file
if self.stream is not None:
self.stream.close()
if self.address is not None:
self.file = wave.open(str(self.address), 'rb')
self.stream = self.pya.open(format=self.pya.get_format_from_width(self.file.getsampwidth()),
channels=self.file.getnchannels(),
rate=self.file.getframerate(),
output=True,
stream_callback=self.callback)
def stop(self):
self.stream.stop_stream()
self.stream.close()
def update(self):
if self.stream is not None:
if not self.stream.is_active():
self.stream.close()
self.play()
def destroy(self):
self.stream.stop_stream()
self.stream.close()
class Sound():
def __init__(self, pya):
self.file = None
self.pya = pya
self.stream = None
self.chunk = 1024
self.channels = 2
self.complete = False
def callback(self, in_data, frame_count, time_info, status):
data = ''
if not self.complete:
data = self.file.readframes(frame_count)
final_pos = self.file.data.tell()
if data == '':
data = self.file.silence*frame_count
if len(data) < self.file.channels*self.file.width*frame_count:
length = self.file.channels*self.file.width*frame_count - len(data)
data += chr(0) * length
if self.complete:
self.complete = False
return data, pyaudio.paComplete
if final_pos == 0:
self.complete = True
return data, pyaudio.paContinue
def play(self, sound_file):
if self.stream is not None:
self.stream.close()
self.file = sound_file
self.stream = self.pya.open(format=self.pya.get_format_from_width(sound_file.width),
channels=sound_file.channels,
rate=sound_file.framerate,
output=True,
stream_callback=self.callback)
def stop(self):
self.stream.stop_stream()
self.stream.close()
def destroy(self):
self.stream.stop_stream()
self.stream.close()
class WaveFile():
def __init__(self, address):
self.file = wave.open(address, 'rb')
self.width = self.file.getsampwidth()
self.channels = self.file.getnchannels()
self.framerate = self.file.getframerate()
self.silence = chr(0)*self.width*self.channels
self.data = cStringIO.StringIO(self.file.readframes(self.file.getnframes()))
self.file.close()
self.complete = False
def readframes(self, frame_count):
data = self.data.read(frame_count*self.channels*self.width)
if self.complete:
self.data.seek(0)
self.complete = False
if self.data.tell() == len(self.data.getvalue()):
self.complete = True
return data
| {
"repo_name": "branderson/PyZelda",
"path": "src/engine/backend/sound.py",
"copies": "1",
"size": "4132",
"license": "mit",
"hash": 1642200993317907200,
"line_mean": 33.4333333333,
"line_max": 104,
"alpha_frac": 0.5493707648,
"autogenerated": false,
"ratio": 3.980732177263969,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5030102942063969,
"avg_score": null,
"num_lines": null
} |
__author__ = 'brad'
import pygame
import pyaudio
import backend
from ctypes import *
from contextlib import contextmanager
ERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int, c_char_p, c_int, c_char_p)
def py_error_handler(filename, line, function, err, fmt):
pass
c_error_handler = ERROR_HANDLER_FUNC(py_error_handler)
@contextmanager
def noalsaerr():
asound = cdll.LoadLibrary('libasound.so.2')
asound.snd_lib_error_set_handler(c_error_handler)
yield
asound.snd_lib_error_set_handler(None)
class ResourceManager(object):
def __init__(self, force_pygame=True, force_pyaudio=True, muted=False):
pygame.font.init()
# pygame.mixer.init()
self.sprites = {}
self.music = {}
self.sounds = {}
self.fonts = {}
self.force_pygame = force_pygame
self.force_pyaudio = force_pyaudio
self.muted = muted
self.current_key = None
with noalsaerr():
self.pya = pyaudio.PyAudio()
self.sound_channels = 4
self.current_sounds = [backend.Sound(self.pya) for x in xrange(self.sound_channels)]
self.sound_queue_index = 0
def add_image(self, key, image):
self.sprites[key] = image
def add_image_list(self, key, images):
self.sprites[key] = images
def add_image_file(self, key, filename):
try:
self.sprites[key] = pygame.image.load(filename).convert_alpha()
return True
except:
return False
def remove_image(self, key):
del self.sprites[key]
def add_image_file_list(self, key, filenames):
self.sprites[key] = []
for filename in filenames:
try:
self.sprites[key].append(pygame.image.load(filename).convert_alpha())
except:
pass
def add_spritesheet_image(self, key, spritesheet, rectangle, colorkey=None):
self.sprites[key] = spritesheet.image_at(rectangle, colorkey)
def add_spritesheet_image_list(self, key, spritesheet, rectangle_list, colorkey=None):
self.sprites[key] = spritesheet.images_at(rectangle_list, colorkey)
def add_spritesheet_strip(self, key, spritesheet, rect, image_count, colorkey=None):
self.sprites[key] = spritesheet.load_strip(rect, image_count, colorkey)
def add_spritesheet_strip_offsets(self, key, spritesheet, topleft, image_count, per_line, image_size, hor_offset,
ver_offset, colorkey=None):
self.sprites[key] = spritesheet.load_strip_offsets(topleft, image_count, per_line, image_size, hor_offset,
ver_offset, colorkey)
def get_images(self, key):
return self.sprites[key]
def add_font(self, key, filename, size):
self.fonts[key] = pygame.font.Font(filename, size)
def remove_font(self, key):
del self.fonts[key]
def add_music(self, key, filename):
# if pyglet.media.have_avbin and not self.force_pygame:
# self.music[key] = pyglet.media.load(filename)
if self.force_pyaudio:
self.music[key] = backend.SoundStream(self.pya, filename)
else:
self.music[key] = filename
def remove_music(self, key):
del self.music[key]
def play_music(self, key, start=0):
if not self.muted:
# if pyglet.media.have_avbin and not self.force_pygame:
# self.music[key].play()
if self.force_pyaudio:
if self.current_key is not None:
self.music[self.current_key].stop()
self.music[key].play()
self.current_key = key
else:
pygame.mixer.music.load(self.music[key])
pygame.mixer.music.play(-1)
# pygame.mixer.music.set_pos(start)
# if pyglet.media.have_avbin and not self.force_pygame:
# self.music[key].play()
def add_sound(self, key, filename):
# if pyglet.media.have_avbin and not self.force_pygame:
# self.sounds[key] = pyglet.media.load(filename, streaming=False)
if self.force_pyaudio:
self.sounds[key] = backend.WaveFile(filename)
else:
self.sounds[key] = pygame.mixer.Sound(filename)
# pass
def remove_sound(self, key):
del self.sounds[key]
def play_sound(self, key):
if not self.muted:
if self.force_pyaudio:
self.current_sounds[self.sound_queue_index].play(self.sounds[key])
self.sound_queue_index += 1
if self.sound_queue_index > self.sound_channels - 1:
self.sound_queue_index = 0
else:
self.sounds[key].play()
# self.current_sounds.append(self.sounds[key])
def update_sound(self):
if self.current_key is not None:
if self.force_pyaudio:
if self.current_key is not None:
self.music[self.current_key].update() | {
"repo_name": "branderson/PyZelda",
"path": "src/engine/resourceman.py",
"copies": "1",
"size": "5061",
"license": "mit",
"hash": -4913173962195845000,
"line_mean": 34.6478873239,
"line_max": 117,
"alpha_frac": 0.5947441217,
"autogenerated": false,
"ratio": 3.5970149253731343,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9679828480996076,
"avg_score": 0.002386113215411864,
"num_lines": 142
} |
__author__ = 'brad'
import pygame
import random
class ObjectState(object):
def __init__(self):
pass
def update(self, game_object, game_scene):
pass
class GameObject(pygame.sprite.Sprite, object):
def __init__(self, image=None, layer=0, masks=None, collision_rect=None, angle=0, position=(0, 0),
handle_collisions=False, object_type=None, properties=None, visible=True, persistent=False,
tile_id=None, animate=False, animation_speed=15, current_frame=0, sync=False, solid=False,
hitbox=None, call_special_update=False):
pygame.sprite.Sprite.__init__(self)
self.images = {}
self.images['image'] = {}
self.images['image'][0] = []
if image is None:
self.images['image'][0].append(pygame.Surface((0, 0)))
else:
try:
len(image)
self.images['image'][0] = image
except TypeError:
self.images['image'][0] = [image]
self.flipped_hor = False
self.flipped_ver = False
self.tinted = None
self.inverted = False
self.visible = visible
self.current_animation = 'image'
self.animate = animate
self.animation_frame = current_frame
self.animation_speed = animation_speed # How many frames to wait between frames
self.animation_counter = 0
self.sync = sync
self.frame_ready = False
self.current_image = self.images['image']
self.current_key = 'image'
if collision_rect is None:
self.collision_rect = self.images['image'][0][0].get_rect()
else:
self.collision_rect = collision_rect
if hitbox is None:
self.hitbox = self.collision_rect
else:
self.hitbox = hitbox
self.rect = self.images['image'][0][0].get_rect()
self._rect_offset = (0, 0)
self.rect_offset = (0, 0)
# self.rect_scaled = self.rect.copy()
# self.rect_draw = self.images['image'].get_rect()
self.layer = layer
self.masks = []
# self.images['image'] = self.image
self.angle = angle
self.scene_position = None
self.position = position
self.states = {}
self._state = None
self.handle_collisions = handle_collisions
self.object_type = object_type
self.persistent = persistent
self.updated = True
self.updated_sprite = False
self.solid = solid
self.remove = False
self.call_special_update = call_special_update
if properties is None:
self.properties = {}
else:
self.properties = properties
for object_property in properties.keys():
if object_property == "solid":
# if properties[property] == "True":
self.solid = True
self.handle_collisions = True
if object_property == "handle_collisions":
self.handle_collisions = True
if object_property == "object_type":
self.object_type = properties[object_property]
if object_property == "collision_rect":
crect_list = map(int, self.properties[object_property].split(','))
self.collision_rect = pygame.Rect(crect_list)
if object_property == "hitbox":
crect_list = map(int, self.properties[object_property].split(','))
self.hitbox = pygame.Rect(crect_list)
self.tile_id = tile_id
# self.rotate(0)
if masks is not None:
for mask in masks:
self.add_mask(mask)
def get_global_rect(self):
return pygame.Rect(self.rect[0] + self.position[0], self.rect[1] + self.position[1], self.rect[2], self.rect[3])
def get_global_collision_rect(self):
return pygame.Rect(self.collision_rect[0] + self.position[0], self.collision_rect[1] + self.position[1],
self.collision_rect[2], self.collision_rect[3])
def get_global_hitbox(self):
return pygame.Rect(self.hitbox[0] + self.position[0], self.hitbox[1] + self.position[1],
self.hitbox[2], self.hitbox[3])
def add_mask(self, mask):
self.masks.append(mask)
def remove_mask(self, mask):
if self.masks.count(mask) != 0:
while self.masks.remove(mask):
pass
def add_image(self, key, surface):
self.images[key] = {}
self.images[key][0] = []
self.images[key][0].append(surface)
def set_image(self, key):
self.updated = True
self.updated_sprite = True
# self.image = self.images[key]
self.current_image = self.images[key]
self.current_key = key
self.animation_frame = 0
self.rect = self.images[self.current_key][self.animation_frame][0].get_rect()
# self.rect = self.current_image[0][0].get_rect()
# self.rotate(0)
def remove_image(self, key):
if key in self.images:
del self.images[key]
def add_animation(self, key, image_list):
self.images[key] = {}
self.images[key][0] = image_list
def set_animation_frame(self, frame):
self.updated = True
self.updated_sprite = True
# self.image = self.images[key][frame]
self.animation_frame = frame
# self.current_image = self.images[key][frame]
# self.rotate(0)
def set_animation(self, key, starting_frame=0):
self.updated = True
self.updated_sprite = True
# self.image = self.images[key][starting_frame]
self.animation_frame = starting_frame
self.current_animation = key
# self.current_image = self.images[key][starting_frame]
self.current_key = key
# self.rotate(0)
def next_frame(self, direction=1):
self.updated = True
self.updated_sprite = True
if direction == -1:
self.animation_frame -= 1
if self.animation_frame < 0:
# self.animation_frame = self.images[self.current_animation].__len__()-1
self.animation_frame = len(self.images[self.current_animation][0])-1
else:
self.animation_frame += 1
if self.animation_frame > len(self.images[self.current_animation][0])-1:
self.animation_frame = 0
if self.animation_frame < len(self.images[self.current_animation][0]):
# self.image = self.images[self.current_animation][self.animation_frame]
# self.current_image = self.images[self.current_animation][self.animation_frame]
# self.rotate(0)
return True
else:
return False
def move(self, coordinate):
self.updated = True
if coordinate is not None:
self.position = coordinate
return True
else:
return False
def increment(self, increment):
return self.move((self.position[0] + increment[0], self.position[1] + increment[1]))
def destroy(self):
del self
return True
def width(self):
return self.rect.width
def height(self):
return self.rect.height
def draw(self, surface, (x, y), invert=False, tint=(0, 0, 0), colorkey=None): # , x_scale, y_scale, x, y):
# TODO: May need to change image to current_image. Also go through and make sure using right image consistently
key = (surface.x_scale, surface.y_scale)
try:
if (invert and not self.inverted) or (not invert and self.inverted):
for image in self.images.keys():
for size in self.images[image].keys():
for frame in xrange(0, len(self.images[image][size])):
self.images[image][size][frame] = self.invert_colors(self.images[image][size][frame],
colorkey=colorkey)
self.inverted = not self.inverted
# TODO: Make this non destructive
# if tint is not None and self.tinted != tint:
# for image in self.images.keys():
# for size in self.images[image].keys():
# for frame in xrange(0, len(self.images[image][size])):
# self.images[image][size][frame] = self.tint(self.images[image][size][frame], tint)
surface.blit(self.tint(self.images[self.current_key][key][self.animation_frame], tint=tint, colorkey=colorkey),
(x, y, self.images[self.current_key][key][self.animation_frame].get_width(),
self.images[self.current_key][key][self.animation_frame].get_height()))
# surface.blit(self.images[self.current_key][key][self.animation_frame],
# (x, y, self.images[self.current_key][key][self.animation_frame].get_width(),
# self.images[self.current_key][key][self.animation_frame].get_height()))
# if tint != (0, 0, 0, 0):
# tint_surface = pygame.Surface(self.images[self.current_key][key][self.animation_frame].get_size())
# tint_surface.fill(tint)
# surface.blit(tint_surface, (x, y))
except IndexError:
print(str(self.animation_frame) + " " + str(len(self.images[self.current_key][key])))
self.updated = False
self.updated_sprite = False
def scale_to_view(self, scaling):
# self.updated = True
# print("Scaling")
for image_list in self.images.keys():
self.images[image_list][scaling] = []
for image in xrange(0, len(self.images[image_list][0])):
self.images[image_list][scaling].append(pygame.transform.scale(self.images[image_list][0][image],
(int(self.images[image_list][0][image].get_width()*scaling[0]),
int(self.images[image_list][0][image].get_height()*scaling[1]))))
# self.images[image_list][0][image][scaling] = pygame.transform.scale(self.images[image_list][image],
# (int(self.images[image_list][image].get_width()*scaling[0]),
# int(self.images[image_list][image].get_height()*scaling[1])))
def rotate(self, angle):
self.angle += angle
rect = self.rect
flipped_image = pygame.transform.flip(self.current_image, self.flipped_hor, self.flipped_ver)
# flipped_image = self.image
self.image = pygame.transform.rotate(flipped_image, self.angle)
# self.image = pygame.transform.flip(self.image, self.flipped_hor, self.flipped_ver)
rect.center = self.image.get_rect().center
self.rect = rect
# Rotates about center, clipping to original width and height
# Don't use this, doesn't work
def rotate_clip(self, angle):
"""rotate an image while keeping its center and size"""
self.angle += angle
rect = self.rect
self.image = pygame.transform.rotate(self.current_image, self.angle)
rect.center = self.image.get_rect().center
self.image = self.image.subsurface(rect).copy()
def flip(self, flip_hor, flip_ver):
if flip_hor:
self.flipped_hor = not self.flipped_hor
if flip_ver:
self.flipped_ver = not self.flipped_ver
self.rotate(0)
@staticmethod
def tint(input_surface, tint, colorkey=None):
if tint == (0, 0, 0) or tint == (0, 0, 0, 0):
return input_surface
else:
surface = input_surface.copy()
tint_surface = pygame.Surface((surface.get_width(), surface.get_height()))
tint_surface.fill(tint)
surface.blit(tint_surface, (0, 0))
# else:
# surface = input_surface.copy()
# surface.lock()
# for x in range(0, surface.get_width()):
# for y in range(0, surface.get_height()):
# pixel = surface.get_at((x, y))
# if pixel != colorkey:
# new_r = pixel.r + tint[0]
# if new_r > 255:
# new_r = 255
# elif new_r < 0:
# new_r = 0
# new_g = pixel.g + tint[1]
# if new_g > 255:
# new_g = 255
# elif new_g < 0:
# new_g = 0
# new_b = pixel.b + tint[2]
# if new_b > 255:
# new_b = 255
# elif new_b < 0:
# new_b = 0
# new_a = pixel.a
# if len(tint) == 4:
# new_a = pixel.a + tint[3]
# if new_a > 255:
# new_a = 255
# elif new_a < 0:
# new_a = 0
# surface.set_at((x, y), (new_r, new_g, new_b, new_a))
# surface.unlock()
return surface
@staticmethod
def invert_colors(input_surface, colorkey=(0, 0, 0)):
surface = input_surface.copy()
surface.lock()
for x in range(0, surface.get_width()):
for y in range(0, surface.get_height()):
pixel = surface.get_at((x, y))
if pixel != colorkey:
new_r = 255 - pixel.r
new_g = 255 - pixel.g
new_b = 255 - pixel.b
a = pixel.a
surface.set_at((x, y), (new_r, new_g, new_b, a))
surface.unlock()
return surface
@staticmethod
def bloom(input_surface, colorkey=(0, 0, 0)):
surface = input_surface.copy()
surface.lock()
for x in range(0, surface.get_width()):
for y in range(0, surface.get_height()):
pixel = surface.get_at((x, y))
if pixel != colorkey:
new_r = 2*pixel.r
new_g = 2*pixel.g
new_b = 2*pixel.b
if new_r > 255:
new_r = 255
if new_g > 255:
new_g = 255
if new_b > 255:
new_b = 255
a = pixel.a
surface.set_at((x, y), (new_r, new_g, new_b, a))
surface.unlock()
return surface
@staticmethod
def gauss(input_surface, colorkey):
surface = input_surface.copy()
surface.lock()
for x in range(0, surface.get_width()):
for y in range(0, surface.get_height()):
pixel = surface.get_at((x, y))
if pixel != colorkey:
arg1 = 30
arg2 = 150
# new_r = pixel.r + random.randrange(-pixel.r, 255 - pixel.r, 1)
# new_g = pixel.g + random.randrange(-pixel.g, 255 - pixel.g, 1)
# new_b = pixel.b + random.randrange(-pixel.b, 255 - pixel.b, 1)
new_r = pixel.r + random.gauss(arg1, arg2)
new_g = pixel.g + random.gauss(arg1, arg2)
new_b = pixel.b + random.gauss(arg1, arg2)
if new_r > 255:
new_r = 255
elif new_r < 0:
new_r = 0
if new_g > 255:
new_g = 255
elif new_g < 0:
new_g = 0
if new_b > 255:
new_b = 255
elif new_b < 0:
new_b = 0
a = pixel.a
surface.set_at((x, y), (new_r, new_g, new_b, a))
surface.unlock()
return surface
def update(self, can_update=True, rewind=False, direction=1):
if self._state is not None:
# self._state.update(self)
pass
if self.animation_speed > 0:
if not rewind:
self.animation_counter += 1
if self.animation_counter >= self.animation_speed:
self.frame_ready = True
if self.frame_ready and can_update:
if not rewind:
self.next_frame(direction)
self.animation_counter = 0
if self.frame_ready:
self.animation_counter = 0
self.frame_ready = False
return True
else:
return False
| {
"repo_name": "branderson/PyZelda",
"path": "src/engine/gameobject.py",
"copies": "1",
"size": "17043",
"license": "mit",
"hash": -1847703564882521000,
"line_mean": 41.1856435644,
"line_max": 145,
"alpha_frac": 0.5088892801,
"autogenerated": false,
"ratio": 3.9323950161513612,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4941284296251361,
"avg_score": null,
"num_lines": null
} |
__author__ = 'brad'
import backend
class CoordinateSurface(backend.Surface):
def __init__(self, rect, coordinate_size):
# This part should be cleaned up
"""The CoordinateSurface is essentially a pygame Surface
with a builtin secondary coordinate system, which operates
irrespectively of the screen coordinates. It holds pointers
to game objects and can manipulate those objects.
:rtype : CoordinateSurface
"""
try:
backend.Surface.__init__(self, (rect.width, rect.height), flags=3)
except:
backend.Surface.__init__(self, (rect[0], rect[1]), flags=3)
self.coordinate_array = {}
self.layers = []
self.x_scale = 1.
self.y_scale = 1.
self.active = True
self.coordinate_width = coordinate_size[0]
self.coordinate_height = coordinate_size[1]
self.x_scale = self.get_width()/float(self.coordinate_width)
self.y_scale = self.get_height()/float(self.coordinate_height)
def insert_object(self, game_object, coordinate):
# TODO: Make return false if object not added.
if coordinate[0] > self.coordinate_width or coordinate[1] > self.coordinate_height:
return False
if coordinate in self.coordinate_array:
self.coordinate_array[coordinate].append(game_object)
else:
self.coordinate_array[coordinate] = [game_object]
if game_object.layer not in self.layers:
self.layers.append(game_object.layer)
self.layers.sort()
return True
def insert_object_centered(self, game_object, coordinate):
# game_object.scale(self.x_scale, self.y_scale)
adjusted_x = coordinate[0] - game_object.rect.centerx
adjusted_y = coordinate[1] - game_object.rect.centery
return self.insert_object(game_object, (adjusted_x, adjusted_y))
def remove_object(self, game_object):
# TODO: Extend to remove all at position
remove_layer = True
for key in self.coordinate_array.keys():
for ob in self.coordinate_array[key]:
if ob.layer == game_object.layer:
remove_layer = False
if remove_layer:
self.layers.remove(game_object.layer)
for key in self.coordinate_array.keys():
if self.coordinate_array[key].count(game_object) > 0:
self.coordinate_array[key].remove(game_object)
if self.coordinate_array[key].__len__() == 0:
del self.coordinate_array[key]
try:
game_object.delete()
except:
pass
return True
return False
def clear(self):
for key in self.coordinate_array.keys():
del self.coordinate_array[key]
self.coordinate_array = {}
self.layers = []
def check_collision(self, coordinate):
if coordinate in self.coordinate_array:
return True
else:
return False
# Returns a list of game objects at position
def check_collision_objects(self, coordinate):
if coordinate in self.coordinate_array:
return self.coordinate_array[coordinate]
else:
return None
def move_object(self, game_object, coordinate):
position = self.check_position(game_object)
# We're gonna need to refactor so that each coordinate is a list of objects
if position is not None:
if coordinate in self.coordinate_array:
self.coordinate_array[coordinate].append(game_object)
else:
self.coordinate_array[coordinate] = [game_object]
self.coordinate_array[position].remove(game_object)
if len(self.coordinate_array[position]) == 0:
del self.coordinate_array[position]
return True
else:
return False
def increment_object(self, game_object, increment):
return self.move_object(game_object, (self.check_position(game_object)[0] + increment[0],
self.check_position(game_object)[1] + increment[1]))
def check_position(self, game_object):
for key in self.coordinate_array.keys():
if self.coordinate_array[key].count(game_object) > 0:
return key
return None
# Convert screen coordinates to game coordinates
def convert_to_surface_coordinates(self, coordinate):
if coordinate[0] > self.get_width() or coordinate[1] > self.get_height():
print("Cannot enter values greater than size of surface")
return
game_x_coordinate = (float(self.coordinate_width)/float(self.get_width()))*coordinate[0]
game_y_coordinate = (float(self.coordinate_height)/float(self.get_height()))*coordinate[1]
return game_x_coordinate, game_y_coordinate
# Convert game coordinates to screen coordinates
def convert_to_screen_coordinates(self, coordinate):
if coordinate[0] > self.coordinate_width or coordinate[1] > self.coordinate_height:
print("Cannot enter values greater than coordinate size of surface")
return
screen_x_coordinate = (float(self.get_width())/float(self.coordinate_width))*coordinate[0]
screen_y_coordinate = (float(self.get_height())/float(self.coordinate_height))*coordinate[1]
# print(str(screen_x_coordinate) + " " + str(screen_y_coordinate))
return screen_x_coordinate, screen_y_coordinate
def update(self, fill=None, masks=None, invert=False, tint=(0, 0, 0), colorkey=None):
if self.active:
# if fill is None:
# self.fill((0, 0, 0, 0))
# else:
# self.fill(fill)
objects = 0
drawn_objects = 0
for layer in self.layers:
for key in self.coordinate_array.keys():
for game_object in self.coordinate_array[key]:
if game_object.layer == layer and game_object.visible:
if masks is None:
if game_object.updated:
self.draw_object(game_object, invert=invert, tint=tint, colorkey=colorkey)
drawn_objects += 1
objects += 1
else:
draw_game_object = False
for mask in masks:
if game_object.masks.count(mask) != 0:
draw_game_object = True
if draw_game_object and game_object.updated:
self.draw_object(game_object, invert=invert, tint=tint, colorkey=colorkey)
drawn_objects += 1
objects += 1
# print(str(objects) + " tiles and objects in the room, " + str(drawn_objects) + " drawn to screen")
# Unusably slow. Don't use except for stills.
def tint(self, (r, g, b, a)):
# TODO: Draw colored surface over surface instead.
self.lock()
for x in range(0, self.get_width() - 1):
for y in range(0, self.get_height() - 1):
new_r = self.get_at((x, y)).r + r
if new_r > 255:
new_r = 255
elif new_r < 0:
new_r = 0
new_g = self.get_at((x, y)).g + g
if new_g > 255:
new_g = 255
elif new_g < 0:
new_g = 0
new_b = self.get_at((x, y)).b + b
if new_b > 255:
new_b = 255
elif new_b < 0:
new_b = 0
new_a = self.get_at((x, y)).a + a
if new_a > 255:
new_a = 255
elif new_a < 0:
new_a = 0
self.set_at((x, y), (new_r, new_g, new_b, new_a))
self.unlock()
def invert_colors(self):
self.lock()
for x in range(0, self.get_width() - 1):
for y in range(0, self.get_height() - 1):
new_r = 255 - self.get_at((x, y)).r
new_g = 255 - self.get_at((x, y)).g
new_b = 255 - self.get_at((x, y)).b
a = self.get_at((x, y)).a
self.set_at((x, y), (new_r, new_g, new_b, a))
self.unlock()
def update_screen_coordinates(self, new_size):
backend.Surface.__init__(self, new_size, flags=1)
self.x_scale = float(self.get_width())/float(self.coordinate_width)
self.y_scale = float(self.get_height())/float(self.coordinate_height)
def update_objects(self):
pass
# Deprecated
def draw_object(self, game_object, invert=False, tint=(0, 0, 0), colorkey=(0, 0, 0)):
x = self.convert_to_screen_coordinates(self.check_position(game_object))[0]
y = self.convert_to_screen_coordinates(self.check_position(game_object))[1]
if not (self.x_scale, self.y_scale) in game_object.current_image.keys():
game_object.scale_to_view((self.x_scale, self.y_scale))
game_object.draw(self, (x, y), invert=invert, tint=tint, colorkey=colorkey)
def draw(self):
return self
# return pygame.transform.scale(self, (int(self.get_width()*self.x_scale), int(self.get_height()*self.y_scale)))
| {
"repo_name": "branderson/PyZelda",
"path": "src/engine/coordsurface.py",
"copies": "1",
"size": "9618",
"license": "mit",
"hash": 6534510860761072000,
"line_mean": 42.9178082192,
"line_max": 120,
"alpha_frac": 0.5498024537,
"autogenerated": false,
"ratio": 4.032704402515724,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5082506856215724,
"avg_score": null,
"num_lines": null
} |
__author__ = 'brad'
import math
import pygame
class Scene(object):
def __init__(self, scene_size, update_all=False, handle_all_collisions=False):
self.coordinate_array = {}
self.collision_array = {}
self.views = {}
self.view_rects = {}
self.view_draw_positions = {}
self.view_update_values = {}
self.active = True
self.scene_width = scene_size[0]
self.scene_height = scene_size[1]
self.update_all = update_all
self.handle_all_collisions = handle_all_collisions
def insert_view(self, surface, key, view_scene_position, view_draw_position=None, fill=None, masks=None,
view_size=None):
if view_size is None:
view_size = (surface.coordinate_width, surface.coordinate_height)
self.views[key] = surface
self.view_rects[key] = pygame.Rect(view_scene_position, view_size)
if view_draw_position is None:
self.view_draw_positions[key] = (0, 0)
else:
self.view_draw_positions[key] = view_draw_position
self.view_update_values[key] = (fill, masks)
def remove_view(self, key):
if key in self.views:
del self.views[key]
del self.view_rects[key]
del self.view_draw_positions[key]
del self.view_update_values[key]
def pan_view(self, key, increment):
self.view_rects[key].x += increment[0]
self.view_rects[key].y += increment[1]
def move_view(self, key, coordinate):
self.view_rects[key].topleft = coordinate
def center_view_on_object(self, key, game_object):
current_view = self.view_rects[key]
self.view_rects[key] = pygame.Rect((self.check_position(game_object)[0] -
current_view.width/2 +
game_object.rect.width/2,
self.check_position(game_object)[1] -
current_view.height/2 + game_object.rect.height/2),
(current_view.width,
current_view.height))
def update_touching_objects(self, game_object):
position = game_object.scene_position
if isinstance(position[0], float) or isinstance(position[1], float):
for other_object in self.list_objects():
other_frame_rect = other_object.images[other_object.current_key][0][other_object.animation_frame].get_rect()
moved_object_rect = pygame.Rect((math.ceil(position[0]) + game_object._rect_offset[0],
math.ceil(position[1]) + game_object._rect_offset[1]),
(game_object.rect.width, game_object.rect.height))
other_object_rect = pygame.Rect((math.ceil(other_object.scene_position[0]) +
other_object._rect_offset[0],
math.ceil(other_object.scene_position[1]) +
other_object._rect_offset[1]),
(other_frame_rect.width,
other_frame_rect.height))
if other_object_rect.colliderect(moved_object_rect):
other_object.updated = True
for other_object in self.list_objects():
try:
other_frame_rect = other_object.images[other_object.current_key][0][other_object.animation_frame].get_rect()
except IndexError:
print(other_object.object_type + " " + other_object.current_key + " " + str(other_object.animation_frame))
moved_object_rect = pygame.Rect((math.floor(position[0]) + game_object._rect_offset[0],
math.floor(position[1]) + game_object._rect_offset[1]),
(game_object.rect.width, game_object.rect.height))
other_object_rect = pygame.Rect((math.floor(other_object.scene_position[0]) +
other_object._rect_offset[0],
math.floor(other_object.scene_position[1]) +
other_object._rect_offset[1]),
(other_frame_rect.width,
other_frame_rect.height))
if other_object_rect.colliderect(moved_object_rect):
other_object.updated = True
def insert_object(self, game_object, coordinate):
game_object.updated = True
if coordinate[0] > self.scene_width or coordinate[1] > self.scene_height:
return False
if coordinate in self.coordinate_array:
self.coordinate_array[coordinate].append(game_object)
else:
self.coordinate_array[coordinate] = [game_object]
game_object.scene_position = coordinate
game_object.position = coordinate
# self.update_touching_objects(game_object)
self.update_collisions()
return True
def insert_object_centered(self, game_object, coordinate):
adjusted_x = coordinate[0] - game_object.rect.centerx
adjusted_y = coordinate[1] - game_object.rect.centery
self.insert_object(game_object, (adjusted_x, adjusted_y))
def remove_object(self, game_object):
self.update_touching_objects(game_object)
self.coordinate_array[game_object.scene_position].remove(game_object)
del game_object
def list_objects(self):
object_list = []
for coordinate in self.coordinate_array.keys():
for game_object in self.coordinate_array[coordinate]:
object_list.append(game_object)
return object_list
def clear(self, key=0):
# TODO: Make default value clear all views, also switch to view.clear()
for coordinate in self.coordinate_array.keys():
del self.coordinate_array[coordinate]
for game_object in self.list_objects():
if self.views[key].checkPosition(game_object) is not None:
self.views[key].remove_object(game_object)
self.update_collisions()
def check_collision(self, coordinate, game_object=None):
"""Checks if any object at position, or if game_object at position"""
self.update_collisions()
if game_object is None:
for rect in self.collision_array.viewitems():
if rect.collidepoint(coordinate):
return True
else:
return False
else:
if game_object in self.collision_array:
if self.collision_array[game_object].collidepoint(coordinate):
return True
return False
def check_collision_objects(self, coordinate):
"""Returns a list of game objects at position"""
self.update_collisions()
object_list = []
for game_object in self.collision_array:
if self.collision_array[game_object].collidepoint(coordinate):
object_list.append(game_object)
return object_list
def check_collision_rect_objects(self, rect):
"""Returns a list of game objects that collide with rect"""
self.update_collisions()
object_list = []
for game_object in self.collision_array:
if self.collision_array[game_object].colliderect(rect):
object_list.append(game_object)
return object_list
def check_object_collision_objects(self, game_object):
"""Returns a list of game objects that collide with object"""
self.update_collisions()
object_list = []
for test_object in self.collision_array:
if self.collision_array[game_object].colliderect(self.collision_array[test_object]) and test_object != game_object:
object_list.append(test_object)
return object_list
def check_object_collision(self, game_object1, game_object2):
"""Checks whether two objects collide"""
# TODO: Add exception if KeyError
self.update_collisions()
if self.collision_array[game_object1].colliderect(self.collision_array[game_object2]):
return True
else:
return False
def check_contain_object(self, game_object1, game_object2):
"""Checks whether game_object1 totally contains game_object2"""
self.update_collisions()
if not self.collision_array[game_object1].collidepoint(self.collision_array[game_object2].topleft):
return False
if not self.collision_array[game_object1].collidepoint(self.collision_array[game_object2].topright):
return False
if not self.collision_array[game_object1].collidepoint(self.collision_array[game_object2].bottomleft):
return False
if not self.collision_array[game_object1].collidepoint(self.collision_array[game_object2].bottomright):
return False
else:
return True
@staticmethod
def move_object(game_object, coordinate):
return game_object.move(coordinate)
@staticmethod
def increment_object(game_object, increment):
return game_object.increment(increment)
@staticmethod
def increment_object_radial(self, game_object, increment):
x_increment = math.cos(math.radians(game_object.angle))*increment
y_increment = math.sin(math.radians(game_object.angle))*increment
return game_object.increment((x_increment, y_increment))
@staticmethod
def check_position(game_object):
# for key in self.coordinate_array.keys():
# if self.coordinate_array[key].count(game_object) > 0:
# return key
return game_object.position
# return None
def update(self, key=0, fill=None, masks=None, invert=False, tint=(0, 0, 0), colorkey=None):
# TODO: Make default key update all views
self.views[key].clear()
update_collisions = False
remove_keys = []
self.update_coordinates()
for coordinate in self.coordinate_array.keys():
if not self.coordinate_array[coordinate]:
remove_keys.append(coordinate)
for coordinate in remove_keys:
self.coordinate_array.pop(coordinate)
for game_object in self.list_objects():
if game_object.updated_sprite:
update_collisions = True
if update_collisions:
self.update_collisions()
for game_object in self.list_objects():
add_object = False
object_rect = pygame.Rect((game_object.position[0] + game_object._rect_offset[0],
game_object.position[1] + game_object._rect_offset[1]),
(game_object.rect.width, game_object.rect.height))
if self.view_rects[key].colliderect(object_rect) and game_object.visible:
if masks is None:
add_object = True
else:
for mask in masks:
if game_object.masks.count(mask) != 0:
add_object = True
if add_object and self.views[key].active:
if game_object.updated:
self.update_touching_objects(game_object)
if self.update_all:
game_object.updated = True
self.views[key].insert_object(game_object, (game_object.position[0] + game_object._rect_offset[0] -
self.view_rects[key].x,
game_object.position[1] + game_object._rect_offset[1] -
self.view_rects[key].y))
self.views[key].update(fill, masks, invert=invert, tint=tint, colorkey=colorkey)
def update_coordinates(self):
for game_object in self.list_objects():
if game_object.remove:
self.remove_object(game_object)
del game_object
elif game_object.updated:
try:
frame_rect = game_object.images[game_object.current_key][0][game_object.animation_frame].get_rect()
except IndexError:
print(game_object.object_type + " " + game_object.current_key + " " + str(game_object.animation_frame))
if game_object.scene_position != game_object.position or game_object.rect != frame_rect:
position = game_object.scene_position
self.update_touching_objects(game_object)
if position is not None:
if game_object.position in self.coordinate_array:
self.coordinate_array[game_object.position].append(game_object)
else:
self.coordinate_array[game_object.position] = [game_object]
if len(self.coordinate_array[position]) == 0:
del self.coordinate_array[position]
self.coordinate_array[position].remove(game_object)
game_object.scene_position = game_object.position
game_object.rect = pygame.Rect((0, 0), (game_object.images[game_object.current_key][0]
[game_object.animation_frame].get_width(),
game_object.images[game_object.current_key][0]
[game_object.animation_frame].get_height()))
game_object._rect_offset = game_object.rect_offset
def update_collisions(self):
self.update_coordinates()
self.collision_array = {}
# objects = []
for game_object in self.list_objects():
# objects.append(game_object)
if game_object.handle_collisions or self.handle_all_collisions: # and game_object.updated:
collide_rect = pygame.Rect((game_object.scene_position[0]+game_object.collision_rect.x,
game_object.scene_position[1]+game_object.collision_rect.y),
(game_object.collision_rect.width, game_object.collision_rect.height))
self.collision_array[game_object] = collide_rect
# remove_objects = []
# for game_object in self.collision_array.keys():
# in_objects = False
# for test_object in objects:
# if game_object == test_object:
# in_objects = True
# if not in_objects:
# remove_objects.append(game_object)
# for game_object in remove_objects:
# self.collision_array.pop(game_object)
def update_screen_coordinates(self, key, new_size):
self.views[key].update_screen_coordinates(new_size)
def update_objects(self):
for view in self.views:
view.update_objects() | {
"repo_name": "branderson/PyZelda",
"path": "src/engine/scene.py",
"copies": "1",
"size": "15417",
"license": "mit",
"hash": -1677391333928915700,
"line_mean": 48.4166666667,
"line_max": 127,
"alpha_frac": 0.5618473114,
"autogenerated": false,
"ratio": 4.236603462489695,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5298450773889696,
"avg_score": null,
"num_lines": null
} |
__author__ = 'brad'
import os
import src.engine as engine # import src.engine as engine
import random
RESOURCE_DIR = os.path.join(os.path.dirname(__file__),'../../resources/') + '/'
SPRITE_DIR = RESOURCE_DIR + 'sprite/'
class AbstractEffect(engine.GameObject):
def __init__(self, object_type):
self.resource_manager = engine.ResourceManager()
self.effect_sheet = engine.Spritesheet(SPRITE_DIR + "Effects.png")
engine.GameObject.__init__(self, layer=100, object_type=object_type)
self.animation_speed = 15
class AbstractShortGrass(AbstractEffect):
def __init__(self, object_type):
AbstractEffect.__init__(self, object_type)
self.direction = 1
def update(self, can_update=True, rewind=False, direction=1):
previous_frame = self.animation_frame
engine.GameObject.update(self, direction=self.direction)
if self.animation_frame != previous_frame:
self.direction = random.choice([1, -1])
class ShortGrass(AbstractShortGrass):
def __init__(self):
AbstractShortGrass.__init__(self, 'effect_short_grass')
self.resource_manager.add_spritesheet_strip_offsets('effect_short_grass', self.effect_sheet,
(0, 0), 3, 3, (16, 16), 0, 0, (64, 64, 192))
self.add_animation('image', self.resource_manager.get_images('effect_short_grass'))
self.set_animation('image', 0)
class ShortForestGrass(AbstractShortGrass):
def __init__(self):
AbstractShortGrass.__init__(self, 'effect_short_forest_grass')
self.resource_manager.add_spritesheet_strip_offsets('effect_short_forest_grass', self.effect_sheet,
(0, 16), 3, 3, (16, 16), 0, 0, (64, 64, 192))
self.add_animation('image', self.resource_manager.get_images('effect_short_forest_grass'))
self.set_animation('image', 0)
class CutGrass(AbstractEffect):
def __init__(self):
AbstractEffect.__init__(self, 'effect_cut_grass')
self.resource_manager.add_spritesheet_strip_offsets('effect_cut_grass', self.effect_sheet,
(0, 32), 8, 8, (32, 32), 0, 0, (64, 64, 192))
self.add_animation('image', self.resource_manager.get_images('effect_cut_grass'))
self.set_animation('image', 0)
self.animation_speed = 2
self.animate = True
def update(self, can_update=True, rewind=False, direction=1):
if self.animation_frame == 7:
self.remove = True
else:
engine.GameObject.update(self)
| {
"repo_name": "branderson/PyZelda",
"path": "src/game/effects.py",
"copies": "1",
"size": "2648",
"license": "mit",
"hash": -8580490143469607000,
"line_mean": 41.0317460317,
"line_max": 107,
"alpha_frac": 0.6087613293,
"autogenerated": false,
"ratio": 3.6373626373626373,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4746123966662637,
"avg_score": null,
"num_lines": null
} |
__author__ = 'brad'
import os
import src.engine as engine
from pygame import Rect
RESOURCE_DIR = os.path.join(os.path.dirname(__file__),'../../resources/') + '/'
SPRITE_DIR = RESOURCE_DIR + 'sprite/'
class LinkSword(engine.GameObject):
def __init__(self, facing, mode="slash"):
self.resource_manager = engine.ResourceManager()
link_sheet = engine.Spritesheet(SPRITE_DIR + "Link.png")
# Load animations
self.resource_manager.add_spritesheet_strip_offsets('link_sword_right', link_sheet, (192, 128), 4, 4, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_sword_up', link_sheet, (128, 128), 4, 4, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_sword_down', link_sheet, (64, 128), 4, 4, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_sword_left', link_sheet, (0, 128), 4, 4, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_sword_spin_clockwise', link_sheet, (0, 144), 8, 8, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_sword_spin_counter', link_sheet, (0, 160), 8, 8, (16, 16), 0, 0, (64, 64, 192))
self.directions = ['link_sword_right', 'link_sword_up', 'link_sword_left', 'link_sword_down']
engine.GameObject.__init__(self, image=self.resource_manager.get_images(self.directions[facing]), layer=25,
persistent=True)
self.add_animation('link_sword_up', self.resource_manager.get_images('link_sword_up'))
self.add_animation('link_sword_down', self.resource_manager.get_images('link_sword_down'))
self.add_animation('link_sword_right', self.resource_manager.get_images('link_sword_right'))
self.add_animation('link_sword_left', self.resource_manager.get_images('link_sword_left'))
self.add_animation('link_sword_spin_clockwise', self.resource_manager.get_images('link_sword_spin_clockwise'))
self.add_animation('link_sword_spin_counter', self.resource_manager.get_images('link_sword_spin_counter'))
self.set_animation(self.directions[facing], 0)
self.animation_speed = 30
self.facing = facing
self.handle_collisions = True
frame_col = {'up': ((3, 10), (1, 6)),
'ur': ((0, 6), (10, 10)),
'right': ((0, 11), (6, 1)),
'dr': ((0, 0), (10, 10)),
'down': ((11, 0), (1, 6)),
'dl': ((6, 0), (10, 10)),
'left': ((10, 11), (6, 1)),
'ul': ((6, 6), (10, 10)),
'right_upper': ((0, 3), (6, 1))}
hit_boxes = {'up': ((2, 4), (6, 12)),
'ur': ((0, 0), (16, 16)),
'right': ((0, 8), (12, 6)),
'dr': ((0, 0), (16, 16)),
'down': ((2, 0), (6, 12)),
'dl': ((0, 0), (16, 16)),
'left': ((4, 8), (12, 6)),
'ul': ((0, 0), (16, 16)),
'right_upper': ((0, 2), (12, 6))}
self.collision_rects = {'link_sword_up': [Rect(frame_col['right_upper']), Rect(frame_col['ur']), Rect(frame_col['up'])],
'link_sword_down': [Rect(frame_col['left']), Rect(frame_col['dl']), Rect(frame_col['down'])],
'link_sword_right': [Rect(frame_col['up']), Rect(frame_col['ur']), Rect(frame_col['right'])],
'link_sword_left': [Rect(frame_col['up']), Rect(frame_col['ul']), Rect(frame_col['left'])],
'link_sword_spin_clockwise': [Rect(frame_col['dr']), Rect(frame_col['down']),
Rect(frame_col['dl']), Rect(frame_col['left']),
Rect(frame_col['ul']), Rect(frame_col['up']),
Rect(frame_col['ur']), Rect(frame_col['right'])],
'link_sword_spin_counter': [Rect(frame_col['dl']), Rect(frame_col['down']),
Rect(frame_col['dr']), Rect(frame_col['right']),
Rect(frame_col['ur']), Rect(frame_col['up']),
Rect(frame_col['ul']), Rect(frame_col['left'])]}
self.hitbox_rects = {'link_sword_up': [Rect(hit_boxes['right_upper']), Rect(hit_boxes['ur']), Rect(hit_boxes['up'])],
'link_sword_down': [Rect(hit_boxes['left']), Rect(hit_boxes['dl']), Rect(hit_boxes['down'])],
'link_sword_right': [Rect(hit_boxes['up']), Rect(hit_boxes['ur']), Rect(hit_boxes['right'])],
'link_sword_left': [Rect(hit_boxes['up']), Rect(hit_boxes['ul']), Rect(hit_boxes['left'])],
'link_sword_spin_clockwise': [Rect(hit_boxes['dr']), Rect(hit_boxes['down']),
Rect(hit_boxes['dl']), Rect(hit_boxes['left']),
Rect(hit_boxes['ul']), Rect(hit_boxes['up']),
Rect(hit_boxes['ur']), Rect(hit_boxes['right'])],
'link_sword_spin_counter': [Rect(hit_boxes['dl']), Rect(hit_boxes['down']),
Rect(hit_boxes['dr']), Rect(hit_boxes['right']),
Rect(hit_boxes['ur']), Rect(hit_boxes['up']),
Rect(hit_boxes['ul']), Rect(hit_boxes['left'])]}
self.call_special_update = True
def update_collisions(self):
self.collision_rect = self.collision_rects[self.current_key][self.animation_frame]
self.hitbox = self.hitbox_rects[self.current_key][self.animation_frame]
def special_update(self, game_scene):
for game_object in game_scene.list_objects():
if game_object.get_global_hitbox().colliderect(self.get_global_hitbox()):
if game_object.object_type == "octorok":
game_scene.remove_object(game_object)
| {
"repo_name": "branderson/PyZelda",
"path": "src/game/linksword.py",
"copies": "1",
"size": "6473",
"license": "mit",
"hash": 9037202522360393000,
"line_mean": 68.6021505376,
"line_max": 147,
"alpha_frac": 0.4835470416,
"autogenerated": false,
"ratio": 3.604120267260579,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9567951856324808,
"avg_score": 0.003943090507154208,
"num_lines": 93
} |
__author__ = 'brad'
import os
import src.engine as engine
import pygame
import effects
import random
import linksword
import specialtiles
from pygame.locals import *
RESOURCE_DIR = os.path.join(os.path.dirname(__file__),'../../resources/') + '/'
SPRITE_DIR = RESOURCE_DIR + 'sprite/'
SOUND_DIR = RESOURCE_DIR + 'sound/'
class Link(engine.GameObject):
def __init__(self, layer=50):
self.resource_manager = engine.ResourceManager()
link_sheet = engine.Spritesheet(SPRITE_DIR + "Link.png")
overworld_sheet = engine.Spritesheet(SPRITE_DIR + "OverworldSheet.png")
self.resource_manager.add_spritesheet_strip_offsets('overworld_tiles', overworld_sheet, (1, 1), 600, 24, (16, 16), 1, 1)
# Load animations
self.resource_manager.add_spritesheet_strip_offsets('link_walk_down', link_sheet, (32, 0), 2, 2, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_walk_up', link_sheet, (64, 0), 2, 2, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_walk_left', link_sheet, (0, 0), 2, 2, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_walk_right', link_sheet, (96, 0), 2, 2, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_push_down', link_sheet, (32, 16), 2, 2, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_push_up', link_sheet, (64, 16), 2, 2, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_push_left', link_sheet, (0, 16), 2, 2, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_push_right', link_sheet, (96, 16), 2, 2, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_shield_walk_down', link_sheet, (32, 32), 2, 2, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_shield_walk_up', link_sheet, (64, 32), 2, 2, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_shield_walk_left', link_sheet, (0, 32), 2, 2, (16, 16), 0, 0, (64, 64, 192)) # These two might be messed up
self.resource_manager.add_spritesheet_strip_offsets('link_shield_walk_right', link_sheet, (96, 32), 2, 2, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_use_shield_down', link_sheet, (32, 48), 2, 2, (16, 16), 0, 0, (64, 64, 192)) # Needs to be fixed
self.resource_manager.add_spritesheet_strip_offsets('link_use_shield_up', link_sheet, (64, 48), 2, 2, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_use_shield_left', link_sheet, (0, 48), 2, 2, (16, 16), 0, 0, (64, 64, 192)) # Take a look at black spot
self.resource_manager.add_spritesheet_strip_offsets('link_use_shield_right', link_sheet, (96, 48), 2, 2, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_hop_down', link_sheet, (0, 64), 3, 3, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_fall', link_sheet, (0, 96), 3, 3, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_sword_down', link_sheet, (32, 112), 2, 2, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_sword_up', link_sheet, (64, 112), 2, 2, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_sword_left', link_sheet, (0, 112), 2, 2, (16, 16), 0, 0, (64, 64, 192))
self.resource_manager.add_spritesheet_strip_offsets('link_sword_right', link_sheet, (96, 112), 2, 2, (16, 16), 0, 0, (64, 64, 192))
engine.GameObject.__init__(self, self.resource_manager.get_images('link_walk_down'), layer,
collision_rect=pygame.Rect((3, 4), (10, 11)),
handle_collisions=True, object_type="player", persistent=True)
# Add animations to Link
self.add_animation('link_walk_up', self.resource_manager.get_images('link_walk_up'))
self.add_animation('link_walk_down', self.resource_manager.get_images('link_walk_down'))
self.add_animation('link_walk_right', self.resource_manager.get_images('link_walk_right'))
self.add_animation('link_walk_left', self.resource_manager.get_images('link_walk_left'))
self.add_animation('link_push_up', self.resource_manager.get_images('link_push_up'))
self.add_animation('link_push_down', self.resource_manager.get_images('link_push_down'))
self.add_animation('link_push_left', self.resource_manager.get_images('link_push_left'))
self.add_animation('link_push_right', self.resource_manager.get_images('link_push_right'))
self.add_animation('link_shield_walk_up', self.resource_manager.get_images('link_shield_walk_up'))
self.add_animation('link_shield_walk_down', self.resource_manager.get_images('link_shield_walk_down'))
self.add_animation('link_shield_walk_right', self.resource_manager.get_images('link_shield_walk_right'))
self.add_animation('link_shield_walk_left', self.resource_manager.get_images('link_shield_walk_left'))
self.add_animation('link_use_shield_up', self.resource_manager.get_images('link_use_shield_up'))
self.add_animation('link_use_shield_down', self.resource_manager.get_images('link_use_shield_down'))
self.add_animation('link_use_shield_left', self.resource_manager.get_images('link_use_shield_left'))
self.add_animation('link_use_shield_right', self.resource_manager.get_images('link_use_shield_right'))
self.add_animation('link_hop_down', self.resource_manager.get_images('link_hop_down'))
self.add_animation('link_fall', self.resource_manager.get_images('link_fall'))
self.add_animation('link_sword_up', self.resource_manager.get_images('link_sword_up'))
self.add_animation('link_sword_down', self.resource_manager.get_images('link_sword_down'))
self.add_animation('link_sword_right', self.resource_manager.get_images('link_sword_right'))
self.add_animation('link_sword_left', self.resource_manager.get_images('link_sword_left'))
# Group animations
self.link_walk = ["link_walk_right", "link_walk_up", "link_walk_left", "link_walk_down"]
self.link_push = ["link_push_right", "link_push_up", "link_push_left", "link_push_down"]
self.link_shield_walk = ["link_shield_walk_right", "link_shield_walk_up", "link_shield_walk_left", "link_shield_walk_down"]
self.link_use_shield = ["link_use_shield_right", "link_use_shield_up", "link_use_shield_left", "link_use_shield_down"]
self.link_sword = ["link_sword_right", "link_sword_up", "link_sword_left", "link_sword_down"]
# Add sounds to Link
self.resource_manager.add_sound('link_hop', SOUND_DIR + 'LA_Link_Jump.wav')
self.resource_manager.add_sound('link_land', SOUND_DIR + 'LA_Link_Land.wav')
self.resource_manager.add_sound('link_shield', SOUND_DIR + 'LA_Shield.wav')
self.resource_manager.add_sound('link_fall', SOUND_DIR + 'LA_Link_Fall.wav')
self.resource_manager.add_sound('link_sword_1', SOUND_DIR + 'LA_Sword_Slash1.wav')
self.resource_manager.add_sound('link_sword_2', SOUND_DIR + 'LA_Sword_Slash2.wav')
self.resource_manager.add_sound('link_sword_3', SOUND_DIR + 'LA_Sword_Slash3.wav')
self.resource_manager.add_sound('link_sword_4', SOUND_DIR + 'LA_Sword_Slash4.wav')
self.resource_manager.add_sound('link_sword_charge', SOUND_DIR + 'LA_Sword_Charge.wav')
self.resource_manager.add_sound('link_sword_spin', SOUND_DIR + 'LA_Sword_Spin.wav')
self.resource_manager.add_sound('link_sword_tap', SOUND_DIR + 'LA_Sword_Tap.wav')
self.resource_manager.add_sound('grass_cut', SOUND_DIR + 'LA_Bush_Cut.wav')
self.sword_slashes = ['link_sword_1', 'link_sword_2', 'link_sword_3', 'link_sword_4']
# Configure Link's properties
self.speed = 1.25 # 1.25
self.movement = {0: (self.speed, 0), 1: (0, -self.speed), 2: (-self.speed, 0), 3: (0, self.speed)}
self.direction = 3
self.facing = 3
self.big_grass = ["big_grass", "big_forest_grass"]
self.short_grass = ["short_grass", "short_forest_grass"]
self.effect_short_grass = ["effect_short_grass", "effect_short_forest_grass"]
self.in_grass = False
self.shield = False
self.left = None
self.right = None
self.controllable = True
self.no_clip = False
self.direction_held = False
self.body_rect = self.rect
self.interaction_rect = None # self.collision_rect.copy()
self.standard_animation_speed = 15
self.solid = True
# Link's States
# self.walk = WalkingState()
# self.collide = CollidingState()
# self.shield = ShieldState()
self._state = WalkingState(self)
self.state = "WalkingState"
def update_interactions(self):
if self.facing == 0:
self.interaction_rect = pygame.Rect((self.position[0]+self.collision_rect.x+self.collision_rect.width,
self.position[1]+self.collision_rect.y),
(1, self.collision_rect.height))
elif self.facing == 1:
self.interaction_rect = pygame.Rect((self.position[0]+self.collision_rect.x,
self.position[1]+self.collision_rect.y-1),
(self.collision_rect.width, 1))
elif self.facing == 2:
self.interaction_rect = pygame.Rect((self.position[0]+self.collision_rect.x-1,
self.position[1]+self.collision_rect.y),
(1, self.collision_rect.height))
elif self.facing == 3:
self.interaction_rect = pygame.Rect((self.position[0]+self.collision_rect.x,
self.position[1]+self.collision_rect.y+self.collision_rect.height),
(self.collision_rect.width, 1))
def update_state(self, game_scene):
self._state.update(self, game_scene)
in_grass = False
grass_type = None
# Short grass effect
for game_object in game_scene.check_object_collision_objects(self):
object_type = game_object.object_type
if object_type in self.short_grass:
in_grass = True
grass_type = object_type
if in_grass and not self.in_grass:
if grass_type == self.short_grass[0]:
game_scene.insert_object(effects.ShortGrass(), self.position)
elif grass_type == self.short_grass[1]:
game_scene.insert_object(effects.ShortForestGrass(), self.position)
self.in_grass = True
elif not in_grass and self.in_grass:
for game_object in game_scene.list_objects():
if game_object.object_type in self.effect_short_grass:
game_scene.remove_object(game_object)
self.in_grass = False
def play_sound(self, key):
self.resource_manager.play_sound(key)
def set_speed(self, speed):
self.speed = speed
self.movement = {0: (self.speed, 0), 1: (0, -self.speed), 2: (-self.speed, 0), 3: (0, self.speed)}
def handle_input(self, game_scene):
if self._state is not None:
self._state.handle_input(self, game_scene)
self.update_interactions()
def handle_event(self, game_scene, event):
if self._state is not None:
self._state.handle_event(self, game_scene, event)
self.update_interactions()
class WalkingState(engine.ObjectState):
def __init__(self, link):
link.state = "WalkingState"
engine.ObjectState.__init__(self)
# Change animations
if not link.shield:
link.set_animation(link.link_walk[link.facing], 0)
else:
link.set_animation(link.link_shield_walk[link.facing], 0)
link.controllable = True
link.animation_speed = link.standard_animation_speed
link.rect_offset = (0, 0)
@staticmethod
def handle_input(link, game_scene):
key = pygame.key.get_pressed()
moves = []
moved = False
# mouse = pygame.mouse.get_pressed()
# if mouse[2]:
# link._state = ShieldState(link)
# Gather movement directions
if not key[K_a] and not key[K_d] and not key[K_w] and not key[K_s] and not key[K_b]:
link.set_animation_frame(0)
else:
if key[K_a] and not key[K_d]:
if not key[K_w] and not key[K_s] and link.facing != 2:
link.facing = 2
if not link.shield:
link.set_animation(link.link_walk[link.facing], 0)
else:
link.set_animation(link.link_shield_walk[link.facing], 0)
link.direction = 2
moves.append(2)
moved = True
elif key[K_d] and not key[K_a]:
if not key[K_w] and not key[K_s] and link.facing != 0:
link.facing = 0
if not link.shield:
link.set_animation(link.link_walk[link.facing], 0)
else:
link.set_animation(link.link_shield_walk[link.facing], 0)
link.direction = 0
moves.append(0)
moved = True
if key[K_s] and not key[K_w]:
if not key[K_d] and not key[K_a] and link.facing != 3:
link.facing = 3
if not link.shield:
link.set_animation(link.link_walk[link.facing], 0)
else:
link.set_animation(link.link_shield_walk[link.facing], 0)
link.direction = 3
moves.append(3)
moved = True
elif key[K_w] and not key[K_s]:
if not key[K_d] and not key[K_a] and link.facing != 1:
link.facing = 1
if not link.shield:
link.set_animation(link.link_walk[link.facing], 0)
else:
link.set_animation(link.link_shield_walk[link.facing], 0)
link.direction = 1
moves.append(1)
moved = True
# Execute movements
if moved:
for move_direction in moves:
previous_position = link.position
link.increment(link.movement[move_direction])
# Deal with collisions
if not link.no_clip:
collisions = []
# Figure out what link is colliding with
for game_object in game_scene.check_object_collision_objects(link):
# Regular collisions, stop movement
if game_object.solid:
collisions.append("solid")
if "slow" in game_object.properties:
collisions.append("slow")
link.set_speed(float(game_object.properties["slow"]))
if game_object.object_type == "hole":
collisions.append("hole")
if game_object.object_type == "jump":
collisions.append("jump")
# if game_object.object_type == "octorok":
# print("Octorok")
if "solid" in collisions:
link.move(previous_position)
link._state = CollidingState(link)
elif "jump" in collisions:
link._state = HoppingState(link)
elif "hole" in collisions:
link._state = SlippingState(link)
#TODO: Fix this
if "slow" not in collisions:
link.set_speed(float(1.25))
# Update and move short grass effect
if link.in_grass:
for game_object in game_scene.list_objects():
if game_object.object_type in link.effect_short_grass:
game_object.move(link.position)
game_object.update()
link.update()
@staticmethod
def handle_event(link, game_scene, event):
if event.type == MOUSEBUTTONDOWN:
button = event.button
if button == 1:
link._state = SwordState(link)
if button == 3:
if link.shield:
link._state = ShieldState(link)
def update(self, link, game_scene):
return
class CollidingState(engine.ObjectState):
def __init__(self, link):
link.state = "CollidingState"
engine.ObjectState.__init__(self)
link.set_animation(link.link_push[link.facing], 0)
link.controllable = True
link.animation_speed = link.standard_animation_speed
link.rect_offset = (0, 0)
@staticmethod
def handle_input(link, game_scene):
key = pygame.key.get_pressed()
moves = []
moved = False
if key[K_a] and not key[K_d]:
if not key[K_w] and not key[K_s] and link.facing != 2:
link.facing = 2
link.set_animation(link.link_push[link.facing], 0)
link.direction = 2
moves.append(2)
moved = True
elif key[K_d] and not key[K_a]:
if not key[K_w] and not key[K_s] and link.facing != 0:
link.facing = 0
link.set_animation(link.link_push[link.facing], 0)
link.direction = 0
moves.append(0)
moved = True
if key[K_s] and not key[K_w]:
if not key[K_d] and not key[K_a] and link.facing != 3:
link.facing = 3
link.set_animation(link.link_push[link.facing], 0)
link.direction = 3
moves.append(3)
moved = True
elif key[K_w] and not key[K_s]:
if not key[K_d] and not key[K_a] and link.facing != 1:
link.facing = 1
link.set_animation(link.link_push[link.facing], 0)
link.direction = 1
moves.append(1)
moved = True
not_colliding_any = True
if moved:
for move_direction in moves:
not_colliding_direction = True
previous_position = link.position
link.increment(link.movement[move_direction])
for game_object in game_scene.check_object_collision_objects(link):
# Regular collisions, stop movement
if game_object.solid and not link.no_clip:
not_colliding_direction = False
not_colliding_any = False
# Stairs
if "slow" in game_object.properties:
link.set_speed(float(game_object.properties["slow"]))
else:
link.set_speed(float(1.25))
if not not_colliding_direction:
link.move(previous_position)
# Update and move short grass effect
if link.in_grass:
for game_object in game_scene.list_objects():
if game_object.object_type in link.effect_short_grass:
game_object.move(link.position)
game_object.update()
link.update()
if not_colliding_any:
link._state = WalkingState(link)
@staticmethod
def handle_event(link, game_scene, event):
if event.type == MOUSEBUTTONDOWN:
button = event.button
if button == 1:
link._state = SwordState(link)
def update(self, link, game_scene):
return
class HoppingState(engine.ObjectState):
def __init__(self, link):
link.state = "HoppingState"
engine.ObjectState.__init__(self)
link.set_animation("link_hop_down", 0)
link.controllable = False
link.animation_counter = 0
link.play_sound("link_hop")
self.hop_frame = 0
link.animation_speed = 15
link.rect_offset = (0, 0)
@staticmethod
def handle_input(link, game_scene):
return
@staticmethod
def handle_event(link, game_scene, event):
pass
def update(self, link, game_scene):
moved = False
for game_object in game_scene.check_object_collision_objects(link):
if game_object.solid or game_object.object_type == "jump":
link.increment((0, 1))
moved = True
if self.hop_frame < 3:
if link.animation_counter >= 7:
link.next_frame(1)
link.animation_counter = 0
self.hop_frame += 1
else:
link.set_animation('link_walk_down', 0)
if not moved:
link.play_sound('link_land')
link._state = WalkingState(link)
# TODO: Slipping should not be a state, can be in other states while slipping. Perhaps hole should pull player in.
class SlippingState(engine.ObjectState):
def __init__(self, link):
engine.ObjectState.__init__(self)
@staticmethod
def handle_input(link, game_scene):
return
@staticmethod
def handle_event(link, game_scene, event):
pass
def update(self, link, game_scene):
return
class FallingState(engine.ObjectState):
def __init__(self, link):
engine.ObjectState.__init__(self)
link._state = WalkingState(link)
@staticmethod
def handle_input(link, game_scene):
return
@staticmethod
def handle_event(link, game_scene, event):
pass
def update(self, link, game_scene):
return
class ShieldState(engine.ObjectState):
def __init__(self, link):
link.state = "ShieldState"
engine.ObjectState.__init__(self)
link.controllable = False
link.set_animation(link.link_use_shield[link.facing], 0)
link.play_sound('link_shield')
link.animation_speed = link.standard_animation_speed
link.rect_offset = (0, 0)
@staticmethod
def handle_input(link, game_scene):
key = pygame.key.get_pressed()
moves = []
moved = False
mouse = pygame.mouse.get_pressed()
# print(str(mouse))
if not mouse[2]:
link._state = WalkingState(link)
# Gather movement directions
if not key[K_a] and not key[K_d] and not key[K_w] and not key[K_s] and not key[K_b]:
link.set_animation_frame(0)
else:
if key[K_a] and not key[K_d]:
if not key[K_w] and not key[K_s] and link.facing != 2:
link.facing = 2
link.set_animation(link.link_use_shield[link.facing], 0)
link.direction = 2
moves.append(2)
moved = True
elif key[K_d] and not key[K_a]:
if not key[K_w] and not key[K_s] and link.facing != 0:
link.facing = 0
link.set_animation(link.link_use_shield[link.facing], 0)
link.direction = 0
moves.append(0)
moved = True
if key[K_s] and not key[K_w]:
if not key[K_d] and not key[K_a] and link.facing != 3:
link.facing = 3
link.set_animation(link.link_use_shield[link.facing], 0)
link.direction = 3
moves.append(3)
moved = True
elif key[K_w] and not key[K_s]:
if not key[K_d] and not key[K_a] and link.facing != 1:
link.facing = 1
link.set_animation(link.link_use_shield[link.facing], 0)
link.direction = 1
moves.append(1)
moved = True
# Execute movements
if moved:
for move_direction in moves:
previous_position = link.position
link.increment(link.movement[move_direction])
# Deal with collisions
if not link.no_clip:
collisions = []
# Figure out what link is colliding with
for game_object in game_scene.check_object_collision_objects(link):
# Regular collisions, stop movement
if game_object.solid:
collisions.append("solid")
if "slow" in game_object.properties:
collisions.append("slow")
link.set_speed(float(game_object.properties["slow"]))
if game_object.object_type == "hole":
collisions.append("hole")
if game_object.object_type == "jump":
collisions.append("jump")
if "solid" in collisions:
link.move(previous_position)
# link._state = CollidingState(link)
elif "jump" in collisions:
link._state = HoppingState(link)
elif "hole" in collisions:
link._state = SlippingState(link)
#TODO: Fix this
if "slow" in collisions:
link.set_speed(float(1.25))
# Update and move short grass effect
if link.in_grass:
for game_object in game_scene.list_objects():
if game_object.object_type in link.effect_short_grass:
game_object.move(link.position)
game_object.update()
link.update()
@staticmethod
def handle_event(link, game_scene, event):
if event.type == MOUSEBUTTONDOWN:
button = event.button
if button == 1:
link._state = SwordState(link)
def update(self, link, game_scene):
return
class SwordState(engine.ObjectState):
def __init__(self, link):
link.state = "SwordState"
engine.ObjectState.__init__(self)
link.set_animation(link.link_sword[link.facing], 0)
link.animation_counter = 0
self.holding = True
self.incremented = False
self.frame = -2
link.animation_speed = 4
link.rect_offset = (0, 0)
# Play random slash sound
link.play_sound(link.sword_slashes[random.randrange(0, 4, 1)])
# Make the sword
self.sword = linksword.LinkSword(link.facing, mode="slash")
self.sword.animation_speed = link.animation_speed / 2
self.inserted = False
self.sword_positions = [[(0, -16), (12, -12), (16, 0)],
[(16, 0), (12, -12), (0, -16)],
[(0, -16), (-12, -12), (-16, 0)],
[(-16, 0), (-12, 12), (0, 16)]]
self.link_movement = [(2, 0), (0, -2), (-2, 0), (0, 2)]
def handle_input(self, link, game_scene):
mouse = pygame.mouse.get_pressed()
# print(str(mouse))
if not mouse[0]:
self.holding = False
def handle_event(self, link, game_scene, event):
if event.type == MOUSEBUTTONDOWN:
button = event.button
if button == 1:
if self.inserted:
game_scene.remove_object(self.sword)
if self.incremented:
link.increment((-1*self.link_movement[link.facing][0], -1*self.link_movement[link.facing][1]))
link._state = SwordState(link)
def update(self, link, game_scene):
if not self.inserted and self.frame == -1:
game_scene.insert_object(self.sword, (link.position[0] + self.sword_positions[link.facing][0][0],
link.position[1] + self.sword_positions[link.facing][0][1]))
self.sword.handle_collisions = False
self.inserted = True
self.frame = 0
if self.frame == -2:
self.frame = -1
if self.sword.animation_frame < 2 and self.inserted:
if self.sword.update():
if self.sword.animation_frame == 1:
link.set_animation_frame(1)
elif self.sword.animation_frame == 2:
link.increment(self.link_movement[link.facing])
self.incremented = True
self.sword.move((link.position[0] + self.sword_positions[link.facing][self.frame][0],
link.position[1] + self.sword_positions[link.facing][self.frame][1]))
if self.sword.animation_frame == 2:
self.sword.handle_collisions = True
self.sword.update_collisions()
if link.update(can_update=False):
self.frame += 1
if self.frame == 5:
link.increment((-1*self.link_movement[link.facing][0], -1*self.link_movement[link.facing][1]))
self.incremented = False
if not self.holding:
mouse = pygame.mouse.get_pressed()
if mouse[2]:
link._state = ShieldState(link)
else:
link._state = WalkingState(link)
else:
link._state = SwordChargeState(link)
game_scene.remove_object(self.sword)
link.updated = True # Don't know why these don't update normally here
self.sword.updated = True
for game_object in game_scene.list_objects():
if game_object.object_type in link.big_grass or game_object.object_type in link.short_grass:
if self.sword.handle_collisions:
if game_object.get_global_rect().colliderect(self.sword.get_global_collision_rect()):
# print(str(self.sword.collision_rect[0]) + ", " + str(self.sword.collision_rect[1]) + ", " +
# str(self.sword.collision_rect[2]) + ", " +str(self.sword.collision_rect[3]))
position = game_object.position
game_scene.remove_object(game_object)
game_scene.insert_object(specialtiles.GroundTile(link.resource_manager), position)
game_scene.insert_object_centered(effects.CutGrass(), (position[0]-8, position[1]-8))
link.resource_manager.play_sound('grass_cut')
class SwordChargeState(engine.ObjectState):
def __init__(self, link):
link.state = "SwordChargeState"
engine.ObjectState.__init__(self)
if link.shield:
link.set_animation(link.link_shield_walk[link.facing], 0)
else:
link.set_animation(link.link_walk[link.facing], 0)
link.animation_frame = 0
self.holding = True
self.charged = False
self.spin = False
self.frame = 0
link.animation_speed = link.standard_animation_speed
self.sword = linksword.LinkSword(link.facing, mode="charge")
self.sword.set_animation_frame(2)
self.sword_positions = [(12, 0), (0, -12), (-12, 0), (0, 12)]
self.inserted = False
def handle_input(self, link, game_scene):
key = pygame.key.get_pressed()
moves = []
moved = False
# Gather movement directions
if not key[K_a] and not key[K_d] and not key[K_w] and not key[K_s] and not key[K_b]:
link.set_animation_frame(0)
else:
if key[K_a] and not key[K_d]:
link.direction = 2
moves.append(2)
moved = True
elif key[K_d] and not key[K_a]:
link.direction = 0
moves.append(0)
moved = True
if key[K_s] and not key[K_w]:
link.direction = 3
moves.append(3)
moved = True
elif key[K_w] and not key[K_s]:
link.direction = 1
moves.append(1)
moved = True
# Execute movements
if moved:
stab = False
for move_direction in moves:
previous_position = link.position
link.increment(link.movement[move_direction])
# Deal with collisions
if not link.no_clip:
collisions = []
# Figure out what link is colliding with
for game_object in game_scene.check_object_collision_objects(link):
# Regular collisions, stop movement
if game_object.solid:
collisions.append("solid")
if move_direction == link.facing:
if game_object.get_global_rect().colliderect(self.sword.get_global_collision_rect()):
stab = True
if "slow" in game_object.properties:
collisions.append("slow")
link.set_speed(float(game_object.properties["slow"]))
if game_object.object_type == "hole":
collisions.append("hole")
if game_object.object_type == "jump":
collisions.append("jump")
if "solid" in collisions:
link.move(previous_position)
# link._state = CollidingState(link)
elif "jump" in collisions:
if self.inserted:
game_scene.remove_object(self.sword)
link._state = HoppingState(link)
elif "hole" in collisions:
if self.inserted:
game_scene.remove_object(self.sword)
link._state = SlippingState(link)
#TODO: Fix this
if "slow" in collisions:
link.set_speed(float(1.25))
if stab and len(moves) == 1:
if self.inserted:
game_scene.remove_object(self.sword)
link._state = SwordStabState(link)
# Update and move short grass effect
if link.in_grass:
for game_object in game_scene.list_objects():
if game_object.object_type in link.effect_short_grass:
game_object.move(link.position)
game_object.update()
link.update()
def handle_event(self, link, game_scene, event):
if event.type == MOUSEBUTTONUP:
button = event.button
if button == 1:
if self.charged:
if self.inserted:
game_scene.remove_object(self.sword)
link._state = SwordSpinState(link)
else:
if self.inserted:
game_scene.remove_object(self.sword)
link._state = WalkingState(link)
def update(self, link, game_scene):
if not self.inserted:
game_scene.insert_object(self.sword, (link.position[0] + self.sword_positions[link.facing][0],
link.position[1] + self.sword_positions[link.facing][1]))
self.inserted = True
else:
self.sword.move((link.position[0] + self.sword_positions[link.facing][0],
link.position[1] + self.sword_positions[link.facing][1]))
if self.charged:
if self.sword.animation_frame == 2 and self.frame % 3 == 0:
self.sword.set_animation_frame(3)
elif self.frame % 3 == 0:
self.sword.set_animation_frame(2)
self.frame += 1
if self.frame == 30:
self.charged = True
link.play_sound('link_sword_charge')
class SwordStabState(engine.ObjectState):
def __init__(self, link):
link.state = "SwordStabState"
engine.ObjectState.__init__(self)
link.controllable = False
link.animation_frame = 0
link.animation_speed = 4
link.animation_counter = 0
self.frame = 0
self.stabbed = False
self.inserted = False
link.set_animation(link.link_sword[link.facing], 1)
self.sword = linksword.LinkSword(link.facing, mode="stab")
self.sword_positions = [(12, 0), (0, -12), (-12, 0), (0, 12)]
self.sword.animation_frame = 2
self.sword.update_collisions()
# print("Stabbing")
@staticmethod
def handle_input(link, game_scene):
return
@staticmethod
def handle_event(link, game_scene, event):
return
def update(self, link, game_scene):
if not self.inserted:
game_scene.insert_object(self.sword, (link.position[0] + self.sword_positions[link.facing][0],
link.position[1] + self.sword_positions[link.facing][1]))
self.inserted = True
if not self.stabbed:
# Figure out what is being stabbed and act accordingly
collisions = []
# Figure out what link is colliding with
for game_object in game_scene.list_objects():
if game_object.object_type in link.big_grass:
if self.sword.handle_collisions:
if game_object.get_global_rect().colliderect(self.sword.get_global_collision_rect()):
# print(str(self.sword.collision_rect[0]) + ", " + str(self.sword.collision_rect[1]) + ", " +
# str(self.sword.collision_rect[2]) + ", " +str(self.sword.collision_rect[3]))
position = game_object.position
game_scene.remove_object(game_object)
game_scene.insert_object(specialtiles.GroundTile(link.resource_manager), position)
game_scene.insert_object_centered(effects.CutGrass(), (position[0]-8, position[1]-8))
collisions.append("big_grass")
elif game_object.solid:
collisions.append("solid")
if "big_grass" in collisions:
link.resource_manager.play_sound('grass_cut')
elif "solid" in collisions:
link.play_sound('link_sword_tap')
self.stabbed = True
if self.frame == 0:
if link.update(can_update=False):
self.frame = 1
if link.facing == 0:
link.increment((2, 0))
self.sword.increment((2, 0))
elif link.facing == 1:
link.increment((0, -2))
self.sword.increment((0, -2))
elif link.facing == 2:
link.increment((-2, 0))
self.sword.increment((-2, 0))
else:
link.increment((0, 2))
self.sword.increment((0, 2))
elif self.frame == 2:
if link.update(can_update=False):
link.set_animation(link.link_walk[link.facing], 0)
if link.facing == 0:
link.increment((-2, 0))
self.sword.increment((-2, 0))
elif link.facing == 1:
link.increment((0, 2))
self.sword.increment((0, 2))
elif link.facing == 2:
link.increment((2, 0))
self.sword.increment((2, 0))
else:
link.increment((0, -2))
self.sword.increment((0, -2))
self.frame += 1
else:
if link.update(can_update=False):
self.frame += 1
if self.frame == 6:
if self.inserted:
game_scene.remove_object(self.sword)
mouse = pygame.mouse.get_pressed()
if mouse[0]:
link._state = SwordChargeState(link)
else:
link._state = WalkingState(link)
class SwordSpinState(engine.ObjectState):
def __init__(self, link):
link.state = "SwordSpinState"
engine.ObjectState.__init__(self)
link.controllable = False
link.animation_frame = 0
link.play_sound('link_sword_spin')
link.animation_speed = 4
link.animation_counter = 0
self.frame = 0
self.positions = {'up': (0, -16), 'ur': (12, -12), 'right': (16, 0), 'dr': (12, 12),
'down': (0, 16), 'dl': (-12, 12), 'left': (-16, 0), 'ul': (-12, -12)}
self.sword = linksword.LinkSword(link.facing, mode="spin")
# self.sword.set_animation_frame(2)
self.sword_positions = [[self.positions['dr'], self.positions['down'], self.positions['dl'], self.positions['left'],
self.positions['ul'], self.positions['up'], self.positions['up'], self.positions['ur'],
self.positions['right']],
[self.positions['ul'], self.positions['left'], self.positions['dl'], self.positions['down'],
self.positions['dr'], self.positions['right'], self.positions['right'], self.positions['ur'],
self.positions['up']],
[self.positions['dl'], self.positions['down'], self.positions['dr'], self.positions['right'],
self.positions['ur'], self.positions['up'], self.positions['up'], self.positions['ul'],
self.positions['left']],
[self.positions['dr'], self.positions['right'], self.positions['ur'], self.positions['up'],
self.positions['ul'], self.positions['left'], self.positions['left'], self.positions['dl'],
self.positions['down']]]
self.link_sprite_indices = [['link_sword_right', 'link_sword_down', 'link_sword_left', 'link_sword_up', 'link_sword_right'],
['link_sword_up', 'link_sword_left', 'link_sword_down', 'link_sword_right', 'link_sword_up'],
['link_sword_left', 'link_sword_down', 'link_sword_right', 'link_sword_up', 'link_sword_left'],
['link_sword_down', 'link_sword_right', 'link_sword_up', 'link_sword_left', 'link_sword_down']]
self.inserted = False
link.set_animation(self.link_sprite_indices[link.facing][0], 1)
if link.facing == 0:
self.sword.set_animation('link_sword_spin_clockwise', 0)
elif link.facing == 1:
self.sword.set_animation('link_sword_spin_counter', 6)
elif link.facing == 2:
self.sword.set_animation('link_sword_spin_counter', 0)
elif link.facing == 3:
self.sword.set_animation('link_sword_spin_counter', 2)
self.sword.update_collisions()
@staticmethod
def handle_input(link, game_scene):
return
@staticmethod
def handle_event(link, game_scene, event):
return
def update(self, link, game_scene):
if not self.inserted:
game_scene.insert_object(self.sword, (link.position[0] + self.sword_positions[link.facing][0][0],
link.position[1] + self.sword_positions[link.facing][0][1]))
self.inserted = True
if link.update(can_update=False):
if self.frame < 8:
self.sword.move((link.position[0] + self.sword_positions[link.facing][self.frame+1][0],
link.position[1] + self.sword_positions[link.facing][self.frame+1][1]))
if self.frame == 1:
link.set_animation(self.link_sprite_indices[link.facing][1], 1)
elif self.frame == 2:
link.set_animation(self.link_sprite_indices[link.facing][2], 1)
elif self.frame == 5:
link.set_animation(self.link_sprite_indices[link.facing][3], 1)
elif self.frame == 7:
link.set_animation(self.link_sprite_indices[link.facing][4], 1)
if self.frame != 5:
self.sword.next_frame(1)
self.sword.update_collisions()
else:
game_scene.remove_object(self.sword)
link._state = WalkingState(link)
self.frame += 1
link.updated = True
self.sword.updated = True
for game_object in game_scene.list_objects():
if game_object.object_type in link.big_grass or game_object.object_type in link.short_grass:
if self.sword.handle_collisions:
if game_object.get_global_rect().colliderect(self.sword.get_global_collision_rect()):
# print(str(self.sword.collision_rect[0]) + ", " + str(self.sword.collision_rect[1]) + ", " +
# str(self.sword.collision_rect[2]) + ", " +str(self.sword.collision_rect[3]))
position = game_object.position
game_scene.remove_object(game_object)
game_scene.insert_object(specialtiles.GroundTile(link.resource_manager), position)
game_scene.insert_object_centered(effects.CutGrass(), (position[0]-8, position[1]-8))
| {
"repo_name": "branderson/PyZelda",
"path": "src/game/link.py",
"copies": "1",
"size": "46634",
"license": "mit",
"hash": 5435727386401376000,
"line_mean": 46.3922764228,
"line_max": 174,
"alpha_frac": 0.5351245872,
"autogenerated": false,
"ratio": 3.8018914071416923,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4837015994341692,
"avg_score": null,
"num_lines": null
} |
__author__ = 'brad'
import os
import src.engine as engine
import pygame
RESOURCE_DIR = os.path.join(os.path.dirname(__file__),'../../resources/') + '/'
FONT_DIR = RESOURCE_DIR + 'font/'
class HUD(engine.CoordinateSurface):
def __init__(self, screen_size):
engine.CoordinateSurface.__init__(self, pygame.Rect((0, 0), (screen_size[0], screen_size[1]/8)), (160, 16))
class TextBox(engine.CoordinateSurface):
def __init__(self, text, screen_size, coordinate_size, justify="center"):
self.scale = (screen_size[0]/coordinate_size[0], screen_size[1]/(coordinate_size[1]+16))
self.width = 144*self.scale[0]
self.height = 40*self.scale[1]
# pygame.Surface.__init__(self, screen_size)
engine.CoordinateSurface.__init__(self, pygame.Rect((0, 0), (self.width, self.height)), (144, 40))
self.fill((0, 0, 0, 255))
self.resource_manager = engine.ResourceManager()
self.resource_manager.add_font('game_text', FONT_DIR + 'zeldadxt.ttf', int(self.scale[1]*12))
self.text = str(text)
self.text_speed = 5
self.frame_counter = 0
self.next_letter = False
self.justify = justify
self.lines = []
self.current_line = 0
self.current_letter = 0
self.waiting = False
self.scrolling = False
self.scroll_frame = 0
self.finished = False
self.rendered_letters = []
self.line_starts = []
self.letter_spacing = 8 * self.scale[0]
line = ""
for char in self.text:
if char != '\\':
line += char
else:
self.lines.append(line)
line = ""
self.lines.append(line)
if self.justify == "center":
for line in self.lines:
letters = len(line)
line_start = self.width/2 - (letters/2)*self.letter_spacing
self.line_starts.append(line_start)
elif self.justify == "left":
for i in xrange (0, len(self.lines)):
self.line_starts.append(8*self.scale[0])
# text_surface = self.resource_manager.fonts['game_text'].render(text, False, (255, 255, 139, 255))
# self.blit(text_surface, (8*scale[0], 8*scale[0]))
def update_text(self):
self.frame_counter += 1
if self.frame_counter >= self.text_speed:
self.next_letter = True
if not self.finished and not self.waiting and not self.scrolling:
if self.next_letter:
self.rendered_letters.append(self.resource_manager.fonts['game_text'].render
(self.lines[self.current_line][self.current_letter], False, (255, 255, 139, 255)))
# self.rendered_letters.append(self.lines[self.current_line][self.current_letter])
self.current_letter += 1
self.draw_letters()
if self.current_letter == len(self.lines[self.current_line]):
self.current_letter = 0
self.current_line += 1
if self.current_line % 2 == 0:
self.waiting = True
if self.current_line == len(self.lines):
self.finished = True
if self.current_line > 1 and not self.waiting:
self.scrolling = True
self.frame_counter = 0
self.next_letter = False
elif not self.finished and self.waiting:
pass
# TODO: Flash the down arrow
if self.scrolling and self.next_letter:
self.scroll_up()
self.frame_counter = 0
self.next_letter = False
def draw_letters(self):
# Draw all of the letters up to the current point
self.fill((0, 0, 0, 255))
if self.current_line >= 1:
line = 0
draw_line = 0
letters = len(self.lines[self.current_line-1]) + self.current_letter
letter = 0
for i in xrange(0, letters):
try:
self.blit(self.rendered_letters[i],
(self.line_starts[self.current_line-1+line] + letter*self.letter_spacing, 6*self.scale[0]+16*self.scale[0]*draw_line))
except IndexError:
print(str(self.current_line) + " " + str(self.current_line-1+line))
letter += 1
if i == len(self.lines[self.current_line-1]) - 1:
draw_line = 1
line += 1
letter = 0
elif self.current_line == 0:
for i in xrange(0, self.current_letter):
# print(str(self.line_starts[0] + i*self.letter_spacing) + ", " + str(8*self.scale[0]))
# print(str(self.line_starts[0]))
self.blit(self.rendered_letters[i], (self.line_starts[0] + i*self.letter_spacing, 6*self.scale[0]))
def scroll_up(self):
# TODO: Scroll text up and delete previous line
# Scrolls up in two increments, deleting previous line on first increment
if self.scroll_frame == 0:
# Deletes line no longer visible
length = len(self.lines[self.current_line-2])
for i in xrange(0, length):
self.rendered_letters.pop(0)
# Scroll up two increments
if self.scroll_frame < 6 and self.scroll_frame % 2 == 0:
scroll_surface = self.copy()
self.fill((0, 0, 0, 255))
self.blit(scroll_surface, (0, -8*self.scale[1]))
self.scroll_frame += 1
else:
self.waiting = False
self.scrolling = False
self.scroll_frame = 0
| {
"repo_name": "branderson/PyZelda",
"path": "src/game/gui.py",
"copies": "1",
"size": "5763",
"license": "mit",
"hash": -3086630491856024600,
"line_mean": 42.3308270677,
"line_max": 148,
"alpha_frac": 0.538434843,
"autogenerated": false,
"ratio": 3.834331337325349,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4872766180325349,
"avg_score": null,
"num_lines": null
} |
__author__ = 'brad'
import os
import src.engine as engine
RESOURCE_DIR = os.path.join(os.path.dirname(__file__),'../../resources/') + '/'
SPRITE_DIR = RESOURCE_DIR + 'sprite/'
class AbstractTile(engine.GameObject):
def __init__(self):
self.resource_manager = engine.ResourceManager()
self.tile_sheet = engine.Spritesheet(SPRITE_DIR + "OverworldSheet.png")
class ShortGrass(AbstractTile):
def __init__(self, resource_manager):
AbstractTile.__init__(self)
engine.GameObject.__init__(self, self.resource_manager.get_images('overworld_tiles')[229],
layer=-500, handle_collisions=True, object_type="short_grass")
class BigBeachGrass(engine.GameObject):
def __init__(self, resource_manager):
engine.GameObject.__init__(self, resource_manager.get_images('overworld_tiles')[254],
layer=-500, handle_collisions=True, object_type="big_beach_grass")
class Hole(engine.GameObject):
def __init__(self, resource_manager):
engine.GameObject.__init__(self, resource_manager.get_images('overworld_tiles')[232],
layer=-500, handle_collisions=True, object_type="big_beach_grass", solid=True)
class GroundTile(AbstractTile):
def __init__(self, resource_manager):
engine.GameObject.__init__(self, resource_manager.get_images('overworld_tiles')[220],
layer=-1000, handle_collisions=False)
| {
"repo_name": "branderson/PyZelda",
"path": "src/game/specialtiles.py",
"copies": "1",
"size": "1495",
"license": "mit",
"hash": -5557264308554162000,
"line_mean": 38.3421052632,
"line_max": 113,
"alpha_frac": 0.6314381271,
"autogenerated": false,
"ratio": 3.7004950495049505,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48319331766049506,
"avg_score": null,
"num_lines": null
} |
__author__ = 'brad'
import pygame
from resourceman import ResourceManager
from spritesheet import Spritesheet
from gameobject import GameObject
import xml.etree.ElementTree as ET
class Map(object):
def __init__(self, filename, tile_set):
"""Takes an XML world file and a tile set and creates a map from it"""
# Load the tile set
self.resource_manager = ResourceManager()
self.object_tiles = {}
self.object_properties = {}
self.tile_set = Spritesheet(tile_set) # Could eventually allow for multiple tile sets by making a list
# TODO: Make spritesheet size independent of class
self.resource_manager.add_spritesheet_strip_offsets('tile_set', self.tile_set, (1, 1), 600, 24, (16, 16), 1, 1)
# Read the XML file
tree = ET.parse(filename)
root = tree.getroot()
self.width = int(root.get("width"))
self.height = int(root.get("height"))
self.tile_width = int(root.get("tilewidth"))
self.tile_height = int(root.get("tileheight"))
# Read in the special tiles
self.special_tiles = {}
for tileset in root.findall("tileset"):
for tile in tileset.findall("tile"):
tile_properties = {}
for tile_property in tile.find("properties").findall("property"):
tile_properties[tile_property.get("name")] = tile_property.get("value")
self.special_tiles[int(tile.get("id"))] = tile_properties
# Read in the layers
self.layers = {}
for layer in root.findall("layer"):
# print(layer.get("name"))
tile_list = []
for tile in layer.find("data").findall("tile"):
# print(tile.get("gid"))
tile_list.append(int(tile.get("gid")))
self.layers[layer.get("name")] = tile_list
# Read in the collision boxes
self.object_layers = {}
for layer in root.findall("objectgroup"):
rect_list = []
rect_index = ""
for object_rect in layer.findall("object"):
try:
current_rect =pygame.Rect(int(object_rect.get("x")), # /self.tile_width,
int(object_rect.get("y")), # /self.tile_height,
int(object_rect.get("width")), # /self.tile_width,
int(object_rect.get("height"))) # /self.tile_height))
rect_list.append(current_rect)
rect_index = str(current_rect[0]) + " " + str(current_rect[1]) + " " + str(current_rect[2]) + " " + str(current_rect[3])
except TypeError:
print("There was a problem loading object at " + str(int(object_rect.get("x"))/self.tile_width)
+ ", " + str(int(object_rect.get("y"))/self.tile_height))
current_properties = {}
if object_rect.get("type") is not None:
current_properties["type"] = object_rect.get("type")
if object_rect.find("properties") is not None:
for object_property in object_rect.find("properties").findall("property"):
current_properties[object_property.get("name")] = object_property.get("value")
if "layer" not in current_properties.keys():
current_properties["layer"] = 0
self.object_properties[rect_index] = current_properties
self.object_layers[layer.get("name")] = rect_list
for layer_property in layer.findall("property"):
if layer_property.get("name") == "tile":
self.object_tiles[layer.get("name")] = int(layer_property.get("value"))
def get_tile_index(self, layer_name, x_tile, y_tile):
index = self.width*y_tile+x_tile
try:
return self.layers[layer_name][index]-1
except IndexError:
return 0
def build_world(self, scene, view_rect=None, current_frame=0):
# This will be deprecated shortly
# print("Starting build")
# self.clear_collisions(scene)
objects = 0
tiles = 0
if view_rect is None:
row = 0
for layer_name in self.layers.keys():
while row < self.height:
for tile in xrange(0, self.width):
current_tile = self.get_tile_index(layer_name, tile, row)
if current_tile != -1:
is_special_tile = False
for special_tile in self.special_tiles.keys():
if current_tile == special_tile:
is_special_tile = True
if is_special_tile:
scene.insert_object(GameObject(self.resource_manager.get_images('tile_set')
[current_tile], -1000, object_type=layer_name,
properties=self.special_tiles[current_tile],
tile_id=current_tile, sync=True),
(16*tile, 16*row))
else:
scene.insert_object(GameObject(self.resource_manager.get_images('tile_set')
[current_tile], -1000, object_type=layer_name,
tile_id=current_tile),
(16*tile, 16*row))
# print(str(row) + " " + str(tile))
row += 1
else:
tile_rect = (view_rect.x/self.tile_width, view_rect.y/self.tile_height,
view_rect.width/self.tile_width, view_rect.height/self.tile_height)
# print(str(view_rect[0]) + " " + str(view_rect[1]) + " " + str(view_rect[2]) + " " + str(view_rect[3]))
# Build the map tiles
for layer_name in self.layers.keys():
row = 0
while row < tile_rect[3]:
for tile in xrange(0, tile_rect[2]):
current_tile = self.get_tile_index(layer_name, tile_rect[0]+tile, tile_rect[1]+row)
if current_tile != -1:
is_special_tile = False
for special_tile in self.special_tiles.keys():
if current_tile == special_tile:
is_special_tile = True
if is_special_tile:
animated = False
frames = 0
# for object_property in self.special_tiles[current_tile].keys():
# if object_property == "animate":
# animated = True
# frames = int(self.special_tiles[current_tile][object_property])
if "animate" in self.special_tiles[current_tile]:
animated = True
frames = int(self.special_tiles[current_tile]["animate"])
if animated:
images = []
for x in xrange(current_tile, current_tile + frames):
images.append(self.resource_manager.get_images('tile_set')[x])
scene.insert_object(GameObject(images, -1000, object_type=layer_name,
properties=self.special_tiles[current_tile],
tile_id=current_tile, animate=True,
current_frame=current_frame, sync=True),
(16*(tile_rect[0]+tile), 16*(tile_rect[1]+row)))
else:
scene.insert_object(GameObject(self.resource_manager.get_images('tile_set')
[current_tile], -1000, object_type=layer_name,
properties=self.special_tiles[current_tile],
tile_id=current_tile),
(16*(tile_rect[0]+tile), 16*(tile_rect[1]+row)))
else:
# Allow it to determine whether objects already exist and just make them visible if they do
scene.insert_object(GameObject(self.resource_manager.get_images('tile_set')
[current_tile], -1000, object_type=layer_name,
tile_id=current_tile),
(16*(tile_rect[0]+tile), 16*(tile_rect[1]+row)))
tiles += 1
# print(str(row) + " " + str(tile))
row += 1
# Build the object layers
for layer_name in self.object_layers.keys():
for object_rect in self.object_layers[layer_name]:
if object_rect.colliderect(view_rect): # tile_rect):
rect_index = str(object_rect[0]) + " " + str(object_rect[1]) + " " + str(object_rect[2]) + " " + str(object_rect[3])
scene.insert_object(GameObject(collision_rect=pygame.Rect(0, 0, object_rect[2], object_rect[3]),
handle_collisions=True, object_type=layer_name, visible=False,
properties=self.object_properties[rect_index],
layer=self.object_properties[rect_index]["layer"]),
(object_rect[0], object_rect[1]))
objects += 1
# print("Added " + str(tiles) + " tiles")
# print("Added " + str(objects) + " objects")
# print("Ending build")
def clear_tiles(self, scene, view_rect, kill_all=False):
# print("Starting to clear tiles")
# handle_all_collisions = scene.handle_all_collisions
# scene.handle_all_collisions = True
# scene.update_collisions()
# scene.handle_all_collisions = handle_all_collisions
self.clear_objects(scene, view_rect)
objects = 0
for coordinate in scene.coordinate_array.keys():
for game_object in scene.coordinate_array[coordinate]:
if game_object.object_type == "Map Tiles":
object_rect = pygame.Rect(scene.check_position(game_object), (game_object.rect.width,
game_object.rect.height))
# try:
# object_rect = scene.collision_array[game_object]
# except KeyError:
# print("an object failed to clear")
if not object_rect.colliderect(view_rect):
if kill_all:
scene.remove_object(game_object)
else:
game_object.visible = False
objects += 1
# scene.update_collisions()
# print("There were " + str(objects) + " tiles")
# print("Ending clear tiles")
# @staticmethod
# def clear_collisions(scene, kill_all=False):
# # print("Starting to clear objects")
# objects = 0
# for coordinate in scene.coordinate_array.keys():
# for game_object in scene.coordinate_array[coordinate]:
# if not game_object.persistent and game_object.object_type == "Regular Collisions":
# scene.remove_object(game_object)
# objects += 1
# # print("There were " + str(objects) + " objects")
# # print("Ending clear objects")
@staticmethod
def clear_objects(scene, view_rect):
for coordinate in scene.coordinate_array.keys():
for game_object in scene.coordinate_array[coordinate]:
if not game_object.persistent and game_object.object_type != "Map Tiles":
object_rect = pygame.Rect(scene.check_position(game_object), (game_object.rect.width,
game_object.rect.height))
if not object_rect.colliderect(view_rect):
scene.remove_object(game_object) | {
"repo_name": "branderson/PyZelda",
"path": "src/engine/map.py",
"copies": "1",
"size": "13218",
"license": "mit",
"hash": -697693512749228700,
"line_mean": 56.2251082251,
"line_max": 140,
"alpha_frac": 0.4665607505,
"autogenerated": false,
"ratio": 4.680594900849858,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5647155651349859,
"avg_score": null,
"num_lines": null
} |
__author__ = 'brad'
import pygame
class Spritesheet(object):
def __init__(self, filename):
try:
self.sheet = pygame.image.load(filename).convert()
except pygame.error, message:
print 'Unable to load spritesheet image:', filename
raise SystemExit, message
# Load image at location
def image_at(self, rectangle, colorkey=None):
"""Loads image from x, y, x+offset, y+offset"""
rect = pygame.Rect(rectangle)
image = pygame.Surface(rect.size).convert()
image.blit(self.sheet, (0, 0), rect)
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0, 0))
image.set_colorkey(colorkey, pygame.RLEACCEL)
return image
# Load a list of images
def images_at(self, rectangle_list, colorkey=None):
return [self.image_at(rectangle, colorkey) for rectangle in rectangle_list]
# Load a strip of images
def load_strip(self, rect, image_count, colorkey=None):
rectangle_list = [(rect[0]+rect[2]*x, rect[1], rect[2], rect[3]) for x in range(image_count)]
return self.images_at(rectangle_list, colorkey)
# Load a stip of images with offsets
def load_strip_offsets(self, topleft, image_count, per_line, image_size, hor_offset=0, ver_offset=0, colorkey=None):
rectangle_list = []
lines = int(image_count/per_line)
even_lines = True
if image_count % per_line != 0:
even_lines = False
current_topleft = topleft
for line in xrange(0, lines):
for image in xrange(0, per_line):
rectangle_list.append(pygame.Rect(current_topleft, (image_size[0], image_size[1])))
current_topleft = (current_topleft[0] + image_size[0] + hor_offset, current_topleft[1])
current_topleft = (topleft[0], current_topleft[1] + image_size[1] + ver_offset)
return self.images_at(rectangle_list, colorkey) | {
"repo_name": "branderson/PyZelda",
"path": "src/engine/spritesheet.py",
"copies": "1",
"size": "2004",
"license": "mit",
"hash": 4134208237051990500,
"line_mean": 40.7708333333,
"line_max": 120,
"alpha_frac": 0.6097804391,
"autogenerated": false,
"ratio": 3.5978456014362656,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4707626040536266,
"avg_score": null,
"num_lines": null
} |
__author__ = 'brad'
import src.engine as engine
import pygame
import random
class AbstractEnemy(engine.GameObject):
def __init__(self):
self.resource_manager = engine.ResourceManager()
engine.GameObject.__init__(self, layer=0, handle_collisions=True, solid=True, object_type="enemy")
class Octorok(AbstractEnemy):
def __init__(self, resource_manager):
AbstractEnemy.__init__(self)
self.resource_manager.add_image_list('octorok_walk_left', [resource_manager.get_images('octorok')[0],
resource_manager.get_images('octorok')[1]])
self.resource_manager.add_image_list('octorok_walk_down', [resource_manager.get_images('octorok')[2],
resource_manager.get_images('octorok')[3]])
self.resource_manager.add_image_list('octorok_walk_up', [resource_manager.get_images('octorok')[4],
resource_manager.get_images('octorok')[5]])
self.resource_manager.add_image_list('octorok_walk_right', [resource_manager.get_images('octorok')[6],
resource_manager.get_images('octorok')[7]])
self.resource_manager.add_image('octorok_missile', resource_manager.get_images('octorok')[8])
self.add_animation('octorok_walk_up', self.resource_manager.get_images('octorok_walk_up'))
self.add_animation('octorok_walk_down', self.resource_manager.get_images('octorok_walk_down'))
self.add_animation('octorok_walk_left', self.resource_manager.get_images('octorok_walk_left'))
self.add_animation('octorok_walk_right', self.resource_manager.get_images('octorok_walk_right'))
self.animations = ['octorok_walk_right', 'octorok_walk_up', 'octorok_walk_left', 'octorok_walk_down']
self.facing = random.randint(0, 3)
self.solid = True
self.hitbox = pygame.Rect((0, 0), (16, 16))
self.object_type = "octorok"
self._state = WalkingState(self)
self.speed = 1.0
self.movement = {0: (self.speed, 0), 1: (0, -self.speed), 2: (-self.speed, 0), 3: (0, self.speed)}
self.mouth = [(16, 2), (2, 0), (0, 2), (2, 16)]
def turn(self):
self.facing = random.randint(0, 3)
self.set_animation(self.animations[self.facing], 0)
class WalkingState(engine.ObjectState):
def __init__(self, octorok):
octorok.state = "WalkingState"
engine.ObjectState.__init__(self)
# Change animations
octorok.set_animation(octorok.animations[octorok.facing], 0)
octorok.collision_rect = octorok.images[octorok.current_key][0][0].get_rect()
self.animation_speed = 15
self.frame = 0
self.shot_counter = 0
self.walking = False
self.missile = octorok.resource_manager.get_images('octorok_missile')
def update(self, octorok, game_scene):
if self.walking:
previous_position = octorok.position
octorok.increment(octorok.movement[octorok.facing])
on_screen = False
for game_object in game_scene.check_object_collision_objects(octorok):
if game_object.solid:
octorok.position = previous_position
self.walking = False
if game_object.object_type == "camera":
if game_scene.check_contain_object(game_object, octorok):
on_screen = True
if not on_screen:
octorok.position = previous_position
self.walking = False
if octorok.update():
self.frame += 1
if self.shot_counter < 8:
self.shot_counter += 1
if self.frame == 5:
self.frame = 0
self.walking = False
else:
if octorok.update(can_update=False):
if self.frame < 2:
self.frame += 1
if self.shot_counter < 8:
self.shot_counter += 1
else:
self.frame = 0
self.walking = True
octorok.turn()
# if self.shot_counter == 8 and self.walking == False:
# missile = Missile(self.missile, octorok.facing)
# game_scene.insert_object(missile, (octorok.position[0] + octorok.mouth[octorok.facing][0],
# octorok.position[1] + octorok.mouth[octorok.facing][1]))
# self.shot_counter = 0
class Missile(engine.GameObject):
def __init__(self, missile_sprite, direction):
engine.GameObject.__init__(self, missile_sprite, handle_collisions=True)
self.speed = 4
self.movement = {0: (self.speed, 0), 1: (0, -self.speed), 2: (-self.speed, 0), 3: (0, self.speed)}
self.direction = direction
self.call_special_update = True
def special_update(self, game_scene):
self.increment(self.movement[self.direction])
on_screen = False
for game_object in game_scene.check_object_collision_objects(self):
if game_object.solid and game_object.object_type != "octorok":
self.remove = True
game_scene.remove_object(self)
if game_object.object_type == "camera":
if game_scene.check_contain_object(game_object, self):
on_screen = True
game_scene.remove_object(self)
if not on_screen:
self.remove = True
| {
"repo_name": "branderson/PyZelda",
"path": "src/game/octorok.py",
"copies": "1",
"size": "5684",
"license": "mit",
"hash": -3163787031724578000,
"line_mean": 46.7647058824,
"line_max": 111,
"alpha_frac": 0.5626319493,
"autogenerated": false,
"ratio": 3.6506101477199744,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.970427045636613,
"avg_score": 0.001794328130768888,
"num_lines": 119
} |
__author__ = 'Brad Urani'
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import numpy as np
import scifipy.histogramhelpers as hh
class PlotHelpers(object):
def __init__(self):
pass
def histogram_with_pdf(self, hist):
mu = hh.hist_mean(hist)
std_dev = hh.hist_std_dev(hist)
width_list = self.width_list(hist)
plt.bar(hist.keys(), hist.values(), width_list, facecolor='g', alpha=0.75)
x = np.linspace(min(hist.keys()), max(hist.keys()), 1000)
plt.plot(x, mlab.normpdf(x, mu, std_dev) * np.mean(width_list), linewidth=5, c='r')
plt.grid(True)
plt.show()
return mu, std_dev
def double_histogram(self, hist1, hist2):
plt.bar(hist1.keys(), hist1.values(), self.width_list(hist1), facecolor='g', alpha=0.5)
plt.bar(hist2.keys(), hist2.values(), self.width_list(hist2), facecolor='b', alpha=0.5)
plt.grid(True)
plt.show()
def width_list(self, hist):
bins = hist.keys()
diffs = [bins[n]-bins[n-1] for n in range(1, len(bins))]
diffs.append(np.mean(diffs)) #add one for the last bar
return diffs
def histogram(self, hist):
plt.bar(hist.keys(), hist.values(), self.width_list(hist), facecolor='g', alpha=0.5)
plt.grid(True)
plt.show() | {
"repo_name": "bradurani/scifipy",
"path": "plothelpers.py",
"copies": "1",
"size": "1335",
"license": "unlicense",
"hash": 8418426080242399000,
"line_mean": 33.2564102564,
"line_max": 95,
"alpha_frac": 0.6037453184,
"autogenerated": false,
"ratio": 3.104651162790698,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4208396481190698,
"avg_score": null,
"num_lines": null
} |
import base64
from urllib.parse import urlsplit
from pprint import pprint # TODO stop logging accesses
from django.http import HttpResponse
from rest_framework import authentication
from rest_framework import exceptions
from .models import LocalCredentials, RemoteCredentials
def createBasicAuthToken(username, password):
"""
This creates an HTTP Basic Auth token from a username and password.
"""
# Format into the HTTP Basic Auth format
tokenString = '{}:{}'.format(username, password)
# Encode into bytes for b64, then into b64
bytesString = tokenString.encode('utf-8')
return base64.b64encode(bytesString)
def parseBasicAuthToken(token):
"""
This parses an HTTP Basic Auth token and returns a tuple of (username,
password).
"""
# Convert the token into a bytes object so b64 can work with it
if isinstance(token, str):
token = token.encode('utf-8')
# Decode from b64 then bytes
parsedBytes = base64.b64decode(token)
parsedString = parsedBytes.decode('utf-8')
# Split out the username, rejoin the password if it had colons
username, *passwordParts = parsedString.split(':')
password = ':'.join(passwordParts)
return (username, password)
def getRemoteCredentials(url):
"""
Finds a remote host that can be used for the given url.
Returns None if it couldn't find.
"""
hostSplit = urlsplit(url)
hostNetloc = hostSplit.netloc
for remoteHost in RemoteCredentials.objects.all():
remoteHostSplit = urlsplit(remoteHost.host)
remoteHostNetloc = remoteHostSplit.netloc
if hostNetloc == remoteHostNetloc:
return remoteHost
return None
class nodeToNodeBasicAuth(authentication.BaseAuthentication):
def authenticate(self, request):
"""
This is an authentication backend for our rest API. It implements
HTTP Basic Auth using admin controlled passwords separate from users.
"""
# TODO stop logging accesses
print(request.method, request.path)
body = request.body.decode('utf-8')
pprint(body)
# Didn't provide auth
print('HTTP_AUTHORIZATION' in request.META)
if 'HTTP_AUTHORIZATION' not in request.META:
raise exceptions.AuthenticationFailed()
auth = request.META['HTTP_AUTHORIZATION']
print('AUTH', auth)
# Tried to auth the wrong way
prefix = 'Basic '
if not auth.startswith(prefix):
raise exceptions.AuthenticationFailed()
# Get username and password
token = auth[len(prefix):]
username, password = parseBasicAuthToken(token)
# TODO stop logging accesses
print('AUTHD WITH: {}, {}\n\n'.format(username, password))
# Fail if these credentials don't exist
try:
creds = LocalCredentials.objects.get(username=username)
except LocalCredentials.DoesNotExist:
raise exceptions.AuthenticationFailed()
# We should probably check their password matches
if creds.password != password:
raise exceptions.AuthenticationFailed()
# These are useful things for auth.. maybe later
return (None, None)
def authenticate_header(self, request):
return 'Basic realm="api"'
| {
"repo_name": "CMPUT404W17T06/CMPUT404-project",
"path": "rest/authUtils.py",
"copies": "1",
"size": "3344",
"license": "apache-2.0",
"hash": 6049982798142617000,
"line_mean": 31.4660194175,
"line_max": 77,
"alpha_frac": 0.6734449761,
"autogenerated": false,
"ratio": 4.531165311653116,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5704610287753116,
"avg_score": null,
"num_lines": null
} |
import uuid
import json
from dash.models import Post, Author
from .verifyUtils import InvalidField, MissingFields, MalformedId, NotFound, \
MalformedBody
def validateData(data, fields):
"""
Validates data in a dictionary using validation functions.
Validation functions should take 3 arguments, the full data (for dependency
validation), the data name, and the data.
Validation functions return an updated, validated version of their value.
Validation functions should raise InvalidField exceptions when they fail to
validate their data or DependencyError if a precondition fails.
"""
for key, validator in fields:
if isinstance(validator, tuple):
if key in data:
try:
validateData(data[key], validator)
except InvalidField as e:
for innerKey in e.data:
raise InvalidField(key + '.' + innerKey,
e.data[innerKey])
else:
raise InvalidField(key, data[key])
elif key in data:
data[key] = validator(data, key, data[key])
def requireFields(data, required):
"""
Ensure that data has required fields. No return on success.
Raises MissingFields if fields are missing from data.
"""
# Make sure we have required fields
notFound = []
for key in required:
# If it's a tuple we need to recurse
if isinstance(key, tuple):
# The key wasn't even sent in the data
if key[0] not in data:
notFound.append(key[0])
# If the data at the key isn't a dict then it's the wrong type
# Say we're missing it and leave early
elif not isinstance(data[key[0]], dict):
notFound.append(key[0])
# If the key is in the data recurse
elif key[0] in data:
# Recurse. Catch missing fields from below and append their
# keys to make the output more useful
try:
requireFields(data[key[0]], key[1])
except MissingFields as e:
for missing in e.data['required']:
notFound.append(key[0] + '.' + missing)
# It was a flat key and just wasn't found
else:
notFound.append(key[0])
# It's not a tuple so it should be a key in this data, append to
# notFound
elif key not in data:
notFound.append(key)
# If we didn't find required keys return an error
if notFound:
raise MissingFields(notFound)
def pidToUrl(request, pid):
"""
Change a URL pid to a locally valid post id URL.
Returns a url string on success or raises MalformedId.
"""
try:
urlUuid = uuid.UUID(pid)
url = 'http://' + request.get_host() + '/posts/' + urlUuid.hex + '/'
except ValueError:
# Include the bad ID in the response
badPath = '/posts/' + pid + '/'
raise MalformedId('post', request.build_absolute_uri(badPath))
return url
def aidToUrl(request, pid):
"""
Change a url aid to a locally valid author id URL.
Returns a url string on success or raises MalformedId.
"""
try:
urlUuid = uuid.UUID(pid)
url = 'http://' + request.get_host() + '/author/' + urlUuid.hex + '/'
except ValueError:
# Include the bad ID in the response
raise MalformedId('author', request.build_absolute_uri(request.path))
return url
def getPost(request, pid):
"""
Get a post by pid in URL.
pid = Post id (uuid4, any valid format available from uuid python lib)
Returns a post object on success, raises NotFound on failure.
"""
# Get url or error response
url = pidToUrl(request, pid)
try:
post = Post.objects.get(id=url)
# Url was valid but post didn't exist
except Post.DoesNotExist:
# Include the bad ID in the response
badPath = '/posts/' + pid + '/'
raise NotFound('post', request.build_absolute_uri(badPath))
return post
def getAuthor(request, aid):
"""
Get an author by aid in URL.
aid = Author id (uuid4, any valid format available from uuid python lib)
Returns an Author object on success, raises NotFound on failure.
"""
# Get url or error response
url = aidToUrl(request, aid)
try:
author = Author.objects.get(id=url)
# Url was valid but author didn't exist
except Author.DoesNotExist:
# Include the bad ID in the response
raise NotFound('author', request.build_absolute_uri(request.path))
return author
def getData(request):
"""
This tries to return valid JSON data from a request.
Raises MalformedBody if POST body wasn't valid JSON.
"""
try:
return json.loads(str(request.body, encoding='utf-8'))
except json.decoder.JSONDecodeError:
raise MalformedBody(request.body)
def getPostData(request):
"""
Returns post data from POST request.
"""
data = getData(request)
# Ensure required fields are present
required = ('author', 'title', 'content', 'contentType', 'visibility')
requireFields(data, required)
return data
def getCommentData(request):
"""
Returns comment data from POST request.
"""
data = getData(request)
# Ensure required fields are present
required = (
'query',
'post',
('comment', (
('author', (
'id',
'host',
'displayName'
)),
'comment',
'contentType',
'published',
'id'
))
)
requireFields(data, required)
return data
def getFriendRequestData(request):
"""
Returns friend request data from POST request.
"""
data = getData(request)
authorRequired = ('id', 'host', 'displayName')
required = (
'query',
('author', authorRequired),
('friend', authorRequired)
)
requireFields(data, required)
return data
def getFriendsListData(request):
"""
Returns data about a multiple friend query.
"""
data = getData(request)
required = (
'query',
'author',
'authors'
)
requireFields(data, required)
return data
| {
"repo_name": "CMPUT404W17T06/CMPUT404-project",
"path": "rest/dataUtils.py",
"copies": "1",
"size": "6464",
"license": "apache-2.0",
"hash": 1300210495638494500,
"line_mean": 28.3818181818,
"line_max": 79,
"alpha_frac": 0.588799505,
"autogenerated": false,
"ratio": 4.34700739744452,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.543580690244452,
"avg_score": null,
"num_lines": null
} |
from django.core.paginator import Paginator, InvalidPage
from rest_framework.views import APIView
from dash.models import Comment, Author, RemoteCommentAuthor
from .serializers import CommentSerializer
from .verifyUtils import addCommentValidators, InvalidField, ResourceConflict, \
DependencyError, NotVisible
from .dataUtils import validateData, getCommentData, getPost
from .httpUtils import JSONResponse
class CommentView(APIView):
"""
This view gets
"""
def get(self, request, pid):
# Try to pull page number out of GET
try:
pageNum = int(request.GET.get('page', 0))
except ValueError:
raise InvalidField('page', request.GET.get('page'))
# Paginator one-indexes for some reason...
pageNum += 1
# Try to pull size out of GET
try:
size = int(request.GET.get('size', 50))
except ValueError:
raise InvalidField('size', request.GET.get('size'))
# Only serve max 100 comments per page
if size > 100:
size = 100
# Get comments and the count
post = getPost(request, pid)
comments = Comment.objects.filter(post=post)
count = comments.count()
# Set up the Paginator
pager = Paginator(comments, size)
# Get our page
try:
page = pager.page(pageNum)
except InvalidPage:
data = {'query': 'comments',
'count': count,
'comments': [],
'size': 0}
if pageNum > pager.num_pages:
# Last page is num_pages - 1 because zero indexed for external
uri = request.build_absolute_uri('?size={}&page={}'\
.format(size,
pager.num_pages - 1))
data['last'] = uri
elif pageNum < 1:
# First page is 0 because zero indexed for external
uri = request.build_absolute_uri('?size={}&page={}'\
.format(size, 0))
data['first'] = uri
else:
# Just reraise the error..
raise
return JSONResponse(data)
# Start our query response
respData = {}
respData['query'] = 'comments'
respData['count'] = count
respData['size'] = size if size < len(page) else len(page)
# Now get our data
comSer = CommentSerializer(page, many=True)
respData['comments'] = comSer.data
# Build and our next/previous uris
# Next if one-indexed pageNum isn't already the page count
if pageNum != pager.num_pages:
# Just use page num, we've already incremented and the external
# inteface is zero indexed
uri = request.build_absolute_uri('?size={}&page={}'\
.format(size, pageNum))
respData['next'] = uri
# Previous if one-indexed pageNum isn't the first page
if pageNum != 1:
# Use pageNum - 2 because we're using one indexed pageNum and the
# external interface is zero indexed
uri = request.build_absolute_uri('?size={}&page={}'\
.format(size, pageNum - 2))
respData['previous'] = uri
return JSONResponse(respData, status=200)
def post(self, request, pid):
"""
This creates comments on posts.
"""
# Get and validate the sent data
data = getCommentData(request)
validateData(data, addCommentValidators)
# See if a comment exists already
try:
comment = Comment.objects.get(id=data['comment']['id'])
# We WANT it to be not found
except Comment.DoesNotExist:
pass
# No error was raised which means it already exists
else:
raise ResourceConflict('comment', data['comment']['id'])
# Get the post this should be attached to
post = getPost(request, pid)
# Check if post is SERVERONLY, they can't post comments to a SERVERONLY
# post (how did they even SEE it?)
if post.visibility == 'SERVERONLY':
raise NotVisible('Access denied: post has SERVERONLY visibility')
# Ensure that the url they POST'd to was the URL they said they were
# posting to
if post.id != data['post']:
data = {'post.id': post.id,
'query.post': data['post']}
raise DependencyError(data)
# Pull out comment specific data
commentData = data['comment']
# Build comment
comment = Comment()
comment.author = commentData['author']['id']
comment.post = post
comment.comment = commentData['comment']
comment.contentType = commentData['contentType']
comment.published = commentData['published']
comment.id = commentData['id']
comment.save()
authorData = commentData['author']
authorId = authorData['id']
# Try to get as a local author
try:
author = Author.objects.get(id=authorId)
# Not a local author, we don't care, just make them remote
except Author.DoesNotExist:
# Try and get remote author, if we find, then update
try:
author = RemoteCommentAuthor.objects.get(authorId=authorId)
author.displayName = authorData['displayName']
author.host = authorData['host']
author.github = authorData.get('github', '')
author.save()
# Didn't exist, so make!
except RemoteCommentAuthor.DoesNotExist:
author = RemoteCommentAuthor()
author.authorId = authorId
author.displayName = authorData['displayName']
author.host = authorData['host']
author.save()
# TODO check if author has visibility,403 if they don't
data = {
"query": "addComment",
"success": True,
"message": "Comment Added"
}
return JSONResponse(data)
| {
"repo_name": "CMPUT404W17T06/CMPUT404-project",
"path": "rest/commentView.py",
"copies": "1",
"size": "6383",
"license": "apache-2.0",
"hash": -7357989257104396000,
"line_mean": 35.0621468927,
"line_max": 80,
"alpha_frac": 0.5489581701,
"autogenerated": false,
"ratio": 4.707227138643068,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5756185308743068,
"avg_score": null,
"num_lines": null
} |
from django.core.paginator import Paginator, InvalidPage
from rest_framework.views import APIView
from dash.models import Post
from .serializers import PostSerializer
from .dataUtils import getAuthor
from .httpUtils import JSONResponse
class AuthorPostView(APIView):
"""
This is for viewing all of the posts that a single author has made.
"""
def get(self, request, aid):
# Try to pull page number out of GET
try:
pageNum = int(request.GET.get('page', 0))
except ValueError:
raise InvalidField('page', request.GET.get('page'))
# Paginator one-indexes for some reason...
pageNum += 1
# Try to pull size out of GET
try:
size = int(request.GET.get('size', 50))
except ValueError:
raise InvalidField('size', request.GET.get('size'))
# Only serve max 100 posts per page
if size > 100:
size = 100
# Get the author
author = getAuthor(request, aid)
# Get their posts and exclude server only and unlisted
posts = Post.objects.filter(author=author) \
.exclude(unlisted=True) \
.exclude(visibility="SERVERONLY")
count = posts.count()
# Set up the Paginator
pager = Paginator(posts, size)
# Get our page
try:
page = pager.page(pageNum)
except InvalidPage:
data = {'query': 'posts',
'count': count,
'posts': [],
'size': 0}
if pageNum > pager.num_pages:
# Last page is num_pages - 1 because zero indexed for external
uri = request.build_absolute_uri('?size={}&page={}'\
.format(size,
pager.num_pages - 1))
data['last'] = uri
elif pageNum < 1:
# First page is 0 because zero indexed for external
uri = request.build_absolute_uri('?size={}&page={}'\
.format(size, 0))
data['first'] = uri
else:
# Just reraise the error..
raise
return JSONResponse(data)
# Start our query response
respData = {}
respData['query'] = 'posts'
respData['count'] = count
respData['size'] = size if size < len(page) else len(page)
# Now get our data
postSer = PostSerializer(page, many=True)
respData['posts'] = postSer.data
# Build and our next/previous uris
# Next if one-indexed pageNum isn't already the page count
if pageNum != pager.num_pages:
# Just use page num, we've already incremented and the external
# inteface is zero indexed
uri = request.build_absolute_uri('?size={}&page={}'\
.format(size, pageNum))
respData['next'] = uri
# Previous if one-indexed pageNum isn't the first page
if pageNum != 1:
# Use pageNum - 2 because we're using one indexed pageNum and the
# external interface is zero indexed
uri = request.build_absolute_uri('?size={}&page={}'\
.format(size, pageNum - 2))
respData['previous'] = uri
return JSONResponse(respData)
| {
"repo_name": "CMPUT404W17T06/CMPUT404-project",
"path": "rest/authorPostView.py",
"copies": "1",
"size": "3559",
"license": "apache-2.0",
"hash": 2794073843567580000,
"line_mean": 34.2376237624,
"line_max": 78,
"alpha_frac": 0.5206518685,
"autogenerated": false,
"ratio": 4.658376963350785,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5679028831850785,
"avg_score": null,
"num_lines": null
} |
from django.core.paginator import Paginator, InvalidPage
from rest_framework.views import APIView
from dash.models import Post
from .serializers import PostSerializer
from .verifyUtils import InvalidField
from .httpUtils import JSONResponse
class PostsView(APIView):
"""
This is the get multiple posts view and uses Pagination to display posts.
"""
def get(self, request):
# Try to pull page number out of GET
try:
pageNum = int(request.GET.get('page', 0))
except ValueError:
raise InvalidField('page', request.GET.get('page'))
# Paginator one-indexes for some reason...
pageNum += 1
# Try to pull size out of GET
try:
size = int(request.GET.get('size', 50))
except ValueError:
raise InvalidField('size', request.GET.get('size'))
# Only serve max 100 posts per page
if size > 100:
size = 100
# Get posts and the count
posts = Post.objects.exclude(visibility='SERVERONLY')
count = posts.count()
# Set up the Paginator
pager = Paginator(posts, size)
# Get our page
try:
page = pager.page(pageNum)
except InvalidPage:
data = {'query': 'posts',
'count': count,
'posts': [],
'size': 0}
if pageNum > pager.num_pages:
# Last page is num_pages - 1 because zero indexed for external
uri = request.build_absolute_uri('?size={}&page={}'\
.format(size,
pager.num_pages - 1))
data['last'] = uri
elif pageNum < 1:
# First page is 0 because zero indexed for external
uri = request.build_absolute_uri('?size={}&page={}'\
.format(size, 0))
data['first'] = uri
else:
# Just reraise the error..
raise
return JSONResponse(data)
# Start our query response
respData = {}
respData['query'] = 'posts'
respData['count'] = count
respData['size'] = size if size < len(page) else len(page)
# Now get our data
postSer = PostSerializer(page, many=True)
respData['posts'] = postSer.data
# Build and our next/previous uris
# Next if one-indexed pageNum isn't already the page count
if pageNum != pager.num_pages:
# Just use page num, we've already incremented and the external
# inteface is zero indexed
uri = request.build_absolute_uri('?size={}&page={}'\
.format(size, pageNum))
respData['next'] = uri
# Previous if one-indexed pageNum isn't the first page
if pageNum != 1:
# Use pageNum - 2 because we're using one indexed pageNum and the
# external interface is zero indexed
uri = request.build_absolute_uri('?size={}&page={}'\
.format(size, pageNum - 2))
respData['previous'] = uri
return JSONResponse(respData, status=200)
| {
"repo_name": "CMPUT404W17T06/CMPUT404-project",
"path": "rest/multiPostView.py",
"copies": "1",
"size": "3369",
"license": "apache-2.0",
"hash": 8388208766356484000,
"line_mean": 34.4631578947,
"line_max": 78,
"alpha_frac": 0.5244879786,
"autogenerated": false,
"ratio": 4.6341127922971115,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0010338555418646952,
"num_lines": 95
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.