from subprocess import getoutput
import argparse, platform

###############################################
#                                             #
#   Us3r Unl0ck3d                             #
#   Author: azazelm3dj3d                      #
#   GitHub: https://github.com/azazelm3dj3d   #
#                                             #
###############################################

parser = argparse.ArgumentParser()
parser.add_argument('-o', '--octal', type=int, default=777, required=False, help="Type your octal as an integer (Ex: 777)")
parser.add_argument('-f', '--file', default=False, required=False, help="Store the output in a file (Format: log_<OCTAL>.txt)", action="store_true")
parser.add_argument('-v', '--verbose', default=False, required=False, help="If outputting to a file, this flag will need to be triggered to also print to the console", action="store_true")
parser.add_argument('-c', '--color', default=False, required=False, help="Add some color! (True by default) | Linux Only", action="store_true")
parser.add_argument('-r', '--recursive', default=False, required=False, help="Recursively search the entire specified directory (May take a long time) | Windows Only", action="store_true")
args = parser.parse_args()

version = "0.2.11"

class Us3rUnl0ck3d:

    def author(self):
        print(f"""
        #################################################################
        #                                                               #
        #   Us3r Unl0ck3d                                               #
        #   Author: azazelm3dj3d                                        #
        #   GitHub: https://github.com/azazelm3dj3d                     #
        #   Repository: https://github.com/azazelm3dj3d/us3r-unl0ck3d   #
        #                                                               #
        #################################################################
        v{version}
        """)

    def main(self):

        def convert_permissions(oct):
            int_to_str_conversion = ""
            perm_values = [(4,"r"),(2,"w"),(1,"x")]

            for int_octal in [int(o) for o in str(oct)]:
                for x, str_octal in perm_values:
                    if int_octal >= x:
                        int_to_str_conversion += str_octal
                        int_octal -= x
                    else:
                        int_to_str_conversion += '-'

            return int_to_str_conversion

        def color_scheme(r, g, b, text):
            if args.color and platform.system() != 'Windows':
                return "\033[38;2;{};{};{}m{} \033[38;2;255;255;255m".format(r, g, b, text)

        whoami = getoutput("whoami")
        whoami_win = getoutput("powershell -Command  (Get-WMIObject -ClassName Win32_ComputerSystem).Username")
        permissions = convert_permissions(args.octal)

        if args.color and platform.system() != 'Windows':
            print("[ {0}]  {1}   Entire Root System (Parameters: /*)"
                .format(color_scheme(0, 255, 0, "0"), color_scheme(0, 255, 0, "=>")))

            print("[ {0}]  {1}   Home Directory (Parameters: ~)"
                .format(color_scheme(0, 255, 0, "1"), color_scheme(0, 255, 0, "=>")))

            print("[ {0}]  {1}   Custom Directory (Ex: /etc)"
                .format(color_scheme(0, 255, 0, "2"), color_scheme(0, 255, 0, "=>")))
        elif platform.system() == 'Windows':
            print("[{0}]  {1}   Entire Root System (Parameters: C:\*)"
                .format("0", "=>"))

            print("[{0}]  {1}   Home Directory (Parameters: ~)"
                .format("1", "=>"))

            print("[{0}]  {1}   Custom Directory (Ex: \Program Files)"
                .format("2", "=>"))
        else:
            print("[{0}]  {1}   Entire Root System (Parameters: /*)"
                .format("0", "=>"))

            print("[{0}]  {1}   Home Directory (Parameters: ~)"
                .format("1", "=>"))

            print("[{0}]  {1}   Custom Directory (Ex: /etc)"
                .format("2", "=>"))

        option = input("Choose Option: ")

        if option == '0':
            if platform.system() == 'Windows':
                if args.recursive:
                    print("This might take awhile...")
                    access_granted = getoutput(f"powershell -Command Get-ChildItem -Recurse C:\* | powershell -Command Get-Acl C:\* | powershell -Command findstr '{whoami_win}'")
                else:
                    access_granted = getoutput(f"powershell -Command Get-ChildItem C:\* | powershell -Command Get-Acl C:\* | powershell -Command findstr '{whoami_win}'")

                print(f"\nSearching system for username: {whoami_win}")
            else:
                access_granted = getoutput(f"ls -la /* | grep '{whoami}' | grep '{permissions}'")

                print(f"\nSearching system for username: {whoami}")
                print(f"Permissions Set: {permissions}")
        elif option == '1':
            if platform.system() == 'Windows':
                if args.recursive:
                    print("This might take awhile...")
                    access_granted = getoutput(f"powershell -Command Get-ChildItem -Recurse ~ | powershell -Command Get-Acl ~ | powershell -Command findstr '{whoami_win}'")
                else:
                    access_granted = getoutput(f"powershell -Command Get-ChildItem ~ | powershell -Command Get-Acl ~ | powershell -Command findstr '{whoami_win}'")

                print(f"\nSearching system for username: {whoami_win}")
            else:
                access_granted = getoutput(f"ls -la ~ | grep '{whoami}' | grep '{permissions}'")

                print(f"\nSearching system for username: {whoami}")
                print(f"Permissions Set: {permissions}")
        elif option == '2':
            dir_name = input("Directory to search: ")

            if platform.system() == 'Windows':
                if args.recursive:
                    print("This might take awhile...")
                    access_granted = getoutput(f"powershell -Command Get-ChildItem -Recurse '{dir_name}' | powershell -Command Get-Acl '{dir_name}' | powershell -Command findstr '{whoami_win}'")
                else:
                    access_granted = getoutput(f"powershell -Command Get-ChildItem '{dir_name}' | powershell -Command Get-Acl '{dir_name}' | powershell -Command findstr '{whoami_win}'")

                print(f"\nSearching system for username: {whoami_win}")
            else:
                access_granted = getoutput(f"ls -la '{dir_name}' | grep '{whoami}' | grep '{permissions}'")

                print(f"\nSearching system for username: {whoami}")
                print(f"Permissions Set: {permissions}")
        else:
            if args.color and platform.system() != 'Windows':
                print("\n{0}\n".format(color_scheme(255, 0, 0, "Unable to search or access system")))
            else:
                print("\n{0}\n".format("Unable to search or access system"))

        try:
            if access_granted != None:

                if args.color and platform.system() != 'Windows':
                    print("\n=== {0} ===\n".format(color_scheme(0, 204, 0, "SEARCH INFO")))
                else:
                    print("\n=== {0} ===\n".format("SEARCH INFO"))

                if platform.system() == 'Windows':
                    print(f"The following files are accessible based the set parameters: {whoami_win}\n")
                else:
                    print(f"The following files are accessible based the set parameters: {permissions}\n")

                if args.file and args.verbose:
                    if platform.system() == 'Windows':
                        print("Path     Owner       Access")
                        print("-" * 50)
                        print(access_granted)
                    else:
                        print(access_granted)
                elif args.file and not args.verbose:
                    print("\nAll data is saved in the generated file")
                else:
                    if platform.system() == 'Windows':
                        print("Path     Owner               Access")
                        print("-" * 50)
                        print(access_granted)
                    else:
                        print(access_granted)

                if args.file:
                    if platform.system() == 'Windows':
                        with open(f'log_{whoami_win}.txt', 'w') as f:
                            f.write("Path     Owner       Access")
                            f.write("-" * 50)
                            f.write(access_granted)
                    else:
                        with open(f'log_{args.octal}.txt', 'w') as f:
                            f.write(access_granted)
            else:
                if args.color and platform.system() != 'Windows':
                    print("\n{0}\n".format(color_scheme(255, 0, 0, "No data was generated")))
                else:
                    print("No data was generated")
        except UnboundLocalError as e:
            if args.color and platform.system() != 'Windows':
                print("\n{0} {1}\n".format(color_scheme(255, 0, 0, "[ERROR] =>"), e))
            else:
                print("[ERROR] => {0}".format(e))

if __name__ == '__main__':
    U3 = Us3rUnl0ck3d()
    U3.author()
    U3.main()


"""Mixins for (API) views in the whole project."""

from bleach import clean
from rest_framework import generics, status
from rest_framework.response import Response

class CleanMixin():
    """Model mixin class which cleans inputs."""

    # Define a map of fields avaialble for import
    SAFE_FIELDS = {}

    def create(self, request, *args, **kwargs):
        """Override to clean data before processing it."""
        serializer = self.get_serializer(data=self.clean_data(request.data))
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def update(self, request, *args, **kwargs):
        """Override to clean data before processing it."""
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=self.clean_data(request.data), partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response(serializer.data)

    def clean_data(self, data: dict) -> dict:
        """Clean / sanitize data.

        This uses mozillas bleach under the hood to disable certain html tags by
        encoding them - this leads to script tags etc. to not work.
        The results can be longer then the input; might make some character combinations
        `ugly`. Prevents XSS on the server-level.

        Args:
            data (dict): Data that should be sanatized.

        Returns:
            dict: Profided data sanatized; still in the same order.
        """
        clean_data = {}
        for k, v in data.items():
            if isinstance(v, str):
                ret = clean(v)
            elif isinstance(v, dict):
                ret = self.clean_data(v)
            else:
                ret = v
            clean_data[k] = ret
        return clean_data

class ListAPI(generics.ListAPIView):
    """View for list API."""

class ListCreateAPI(CleanMixin, generics.ListCreateAPIView):
    """View for list and create API."""

class CreateAPI(CleanMixin, generics.CreateAPIView):
    """View for create API."""

class RetrieveAPI(generics.RetrieveAPIView):
    """View for retreive API."""
    pass

class RetrieveUpdateAPI(CleanMixin, generics.RetrieveUpdateAPIView):
    """View for retrieve and update API."""
    pass

class RetrieveUpdateDestroyAPI(CleanMixin, generics.RetrieveUpdateDestroyAPIView):
    """View for retrieve, update and destroy API."""

class UpdateAPI(CleanMixin, generics.UpdateAPIView):
    """View for update API."""


# Advent of Code day 12, part 2, Hot Springs.
# https://adventofcode.com/2023/day/12

from icecream import ic
import functools

# From, https://medium.com/@nkhaja/memoization-and-decorators-with-python-32f607439f84
def memoize(func):
    cache = func.cache = {}
    @functools.wraps(func)
    def memoized_func(*args, **kwargs):
        key = str(args) + str(kwargs)
        if key not in cache:
            cache[key] = func(*args, **kwargs)
        return cache[key]
    return memoized_func

@memoize
def solution(condition_records: list, groups: list, banked_springs: int) -> int:

    # Success!
    if len(condition_records) == 0 and len(groups) == 0 and banked_springs == 0:
        return 1

    # Basic failure.
    if len(condition_records) == 0:
        return 0

    new_condition_records = condition_records.copy()
    front_condition = new_condition_records.pop(0)

    if front_condition == '#':
        return solution(new_condition_records, groups, banked_springs + 1)

    if front_condition == '.':
        if banked_springs == 0:         # One of a line of consecutive dots, so skip.
            return solution(new_condition_records, groups, banked_springs)

        if len(groups) == 0:
            return 0

        new_groups = groups.copy()
        front_group = new_groups.pop(0)

        # Failure: the group we are about to close has incorrect number of springs in it.
        if banked_springs != front_group:
            return 0

        return solution(new_condition_records, new_groups, 0)   # Start a new group.

    else:                           # Must be a question mark.
        new_condition_records2 = new_condition_records.copy()

        new_condition_records.insert(0, '.')
        new_condition_records2.insert(0, '#')

        return (solution(new_condition_records, groups, banked_springs)
                + solution(new_condition_records2, groups, banked_springs))

def process(line: str) -> int:
    condition_records_str, groups_str = line.split(' ')

    condition_record = [each for each in condition_records_str]
    groups = [int(group) for group in groups_str.split(',')]

    unfolded_condition_record = []
    for i in range(4):
        unfolded_condition_record += condition_record
        unfolded_condition_record.append('?')
    unfolded_condition_record += condition_record
    unfolded_condition_record.append('.')

    unfolded_groups = groups * 5
    return solution(unfolded_condition_record, unfolded_groups, 0)

with open('input.txt', 'r') as file:
    conditions = file.read()

total, line_no = 0, 0
for line in conditions.split('\n'):
    line_no += 1

    arrangements = process(line)
    ic(line_no, line, arrangements)
    total += arrangements

ic(total)


#!/usr/bin/python3

from PIL import Image
import os
import array
import time
import sys
import argparse
from ctypes import *
import numpy

numpy.set_printoptions(threshold=numpy.nan)
numpy.set_printoptions(linewidth=2000)

colorScheme = numpy.array([(0x00, 0x00, 0x8F), \
                           (0x00, 0x0F, 0xFF), \
                           (0x00, 0x8F, 0xFF), \
                           (0x00, 0xCF, 0xFF), \
                           (0x0F, 0xFF, 0xEF), \
                           (0x4F, 0xFF, 0xAF), \
                           (0x8F, 0xFF, 0x6F), \
                           (0xCF, 0xFF, 0x2F), \
                           (0xFF, 0xEF, 0x00), \
                           (0xFF, 0xAF, 0x00), \
                           (0xFF, 0x9F, 0x00), \
                           (0xFF, 0x6F, 0x00), \
                           (0xFF, 0x2F, 0x00), \
                           (0xEF, 0x00, 0x00), \
                           (0xAF, 0x00, 0x00), \
                           (0x7F, 0x00, 0x00)])

#fDisp = open('cDisp.txt', 'r')

disp = numpy.loadtxt('cDisp.txt', dtype='int')
[dispH, dispW] = disp.shape

sad = numpy.loadtxt('cSadVals_7x7.txt', dtype='int')
[sadH, sadW] = sad.shape

'''for i in range(282): #280
    for j in range(363): #361
        if (disp[i][j] > 15):
            disp[i][j] = 15'''

# create disparity image
im = Image.new("RGB", (dispW, dispH), "white")

for i in range(dispW):
    for j in range(dispH):
        if (sad[j][i] < 4096):
            im.putpixel((i,j), (colorScheme[disp[j][i]][0], colorScheme[disp[j][i]][1], colorScheme[disp[j][i]][2]))
        else:
            im.putpixel((i,j), (0x00, 0x00, 0x00))
            print("sad[%d][%d]", i, j)

im.save("tsukuba_largeVal_7x7.png")
im.show()

#fDisp.close()


import requests
from pathlib import Path

class WeatherForecast:
    """
    {
        "state": "晴れ",
        "max": "13℃",
        "min": "5℃",
        "max_diff": "[-5]",
        "min_diff": "[0]",
        "icon": "https://s.yimg.jp/images/weather/general/next/size150/100_night.png",
        "rainy-percent": [
            "---",
            "---",
            "---",
            "0%"
        ]
    }
    """
    def __init__(self, api_url):
        self.TIME_OUT = (3, 6)
        self.USER_AGENT = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36'}
        self.api_url = api_url

    def fetch_weather_forecast(self):
        forecast_dict = {}
        try:
            res = requests.get(self.api_url, headers=self.USER_AGENT, timeout=self.TIME_OUT)
            if res.status_code == 200:
                forecast = res.json()['forecasts'][0]

                forecast_dict['state'] = forecast['telop']
                forecast_dict['max'] = forecast['temperature']['max']['celsius']
                forecast_dict['max_diff'] = ''
                forecast_dict['min'] = forecast['temperature']['min']['celsius']
                forecast_dict['min_diff'] = ''
                forecast_dict['icon'] = forecast['image']['url']
                forecast_dict['rainy_percent'] = [percent for percent in forecast['chanceOfRain'].values()]
            else:
                forecast_dict['error'] = 'Status Code:{} From:{}'.format(res.status_code, self.api_url)
        except Exception as e:
            forecast_dict['error'] = str(e)

        return forecast_dict

    def fetch_forecast_icon(self, root_dir, src_url):
        file_name = src_url.split('/')[-1]
        image_dir = Path(root_dir.parent).joinpath('public/images')
        image_file_path = Path(image_dir).joinpath(file_name)
        try:
            res = requests.get(src_url, headers=self.USER_AGENT, timeout=self.TIME_OUT)
            image = res.content
            # imagesフォルダなかったら作成
            if not image_dir.is_dir(): Path.mkdir(image_dir)
            # 画像保存
            with open(image_file_path, 'wb') as f:
                f.write(image)

            # 画像ファイルのフルパスを返す
            if Path(image_file_path).exists():
                return str(image_file_path)
            else:
                return False
        except Exception as e:
            return str(e)


"""
Pushes new music library data up into the cloud (i.e. the AppEngine
data store).  This causes the newly-added tracks to appear in the DJ
database and other chirpradio apps.

TODO(trow): Some of this is a bit hacky; it was put together quickly
to do the initial import.  It needs cleaning up before it can be put
into general use.
"""

import datetime
import re
import sys
import time
import urllib2

from chirp.common.printing import cprint
from chirp.common import timestamp
from chirp.common import conf
from chirp.library import album
from chirp.library import constants
from chirp.library import database
from chirp.library import order
from chirp.library import titles

from chirp.common import chirpradio
from google.appengine.ext import db
from djdb import models
from djdb import search

START_TIMESTAMP = 0
start_at_flag = "--start-at="
for arg in sys.argv:
    if arg.startswith(start_at_flag):
        arg = arg[len(start_at_flag):]
        START_TIMESTAMP = timestamp.parse_human_readable(arg)
        break

# TODO(trow): Is this optimal?
_NUM_ALBUMS_PER_FLUSH = 3

_DISC_NUM_RE = re.compile("disc\s+(\d+)", re.IGNORECASE)

_artist_cache = {}

DRY_RUN = False

class UnknownArtistError(Exception):
    pass

def get_artist_by_name(name):
    global _artist_cache
    if name in _artist_cache:
        return _artist_cache[name]
    while True:
        try:
            art = models.Artist.fetch_by_name(name)
            if art is None:
                raise UnknownArtistError("Unknown artist: %s" % name)
            _artist_cache[name] = art
            return art
        except urllib2.URLError:
            cprint("Retrying fetch_by_name for '%s'" % name)

def seen_album(album_id):
    while True:
        try:
            for alb in models.Album.all().filter("album_id =", album_id):
                if not alb.revoked:
                    return True
            return False
        except urllib2.URLError:
            cprint("Retrying fetch of album_id=%s" % album_id)

def process_one_album(idx, alb):
    # Build up an Album entity.
    kwargs = {}
    kwargs["parent"] = idx.transaction
    kwargs["title"] = alb.title()
    kwargs["album_id"] = alb.album_id
    kwargs["import_timestamp"] = datetime.datetime.utcfromtimestamp(
        alb.import_timestamp())
    kwargs["num_tracks"] = len(alb.all_au_files)
    kwargs["import_tags"] = alb.tags()

    if alb.is_compilation():
        kwargs["is_compilation"] = True
    else:
        kwargs["is_compilation"] = False
        kwargs["album_artist"] = get_artist_by_name(alb.artist_name())

    for key, val in sorted(kwargs.iteritems()):
        cprint("%s: %s" % (key, val))
    if seen_album(alb.album_id):
        cprint("   Skipping")
        return

    album = models.Album(**kwargs)

    # Look for a disc number in the tags.
    for tag in kwargs["import_tags"]:
        m = _DISC_NUM_RE.search(tag)
        if m:
            album.disc_number = int(m.group(1))
            break

    idx.add_album(album)

    for au_file in alb.all_au_files:
        track_title, import_tags = titles.split_tags(au_file.tit2())
        track_num, _ = order.decode(unicode(au_file.mutagen_id3["TRCK"]))
        kwargs = {}
        if alb.is_compilation():
            kwargs["track_artist"] = get_artist_by_name(au_file.tpe1())
        track = models.Track(
            parent=idx.transaction,
            ufid=au_file.ufid(),
            album=album,
            title=track_title,
            import_tags=import_tags,
            track_num=track_num,
            sampling_rate_hz=au_file.mp3_header.sampling_rate_hz,
            bit_rate_kbps=int(au_file.mp3_header.bit_rate_kbps),
            channels=au_file.mp3_header.channels_str,
            duration_ms=au_file.duration_ms,
            **kwargs)
        idx.add_track(track)

def flush(list_of_pending_albums):
    if not list_of_pending_albums:
        return
    if DRY_RUN:
        cprint("Dry run -- skipped flush")
        return
    idx = search.Indexer()
    for alb in list_of_pending_albums:
        process_one_album(idx, alb)
    # This runs as a batch job, so set a very long deadline.
    while True:
        try:
            rpc = db.create_rpc(deadline=120)
            idx.save(rpc=rpc)
            return
        except urllib2.URLError:
            cprint("Retrying indexer flush")

def maybe_flush(list_of_pending_albums):
    if len(list_of_pending_albums) < _NUM_ALBUMS_PER_FLUSH:
        return list_of_pending_albums
    flush(list_of_pending_albums)
    return []

def main():
    for _ in main_generator(START_TIMESTAMP):
        pass

def main_generator(start_timestamp):
    #chirpradio.connect("10.0.1.98:8000")
    chirpradio.connect()

    sql_db = database.Database(conf.LIBRARY_DB)
    pending_albums = []
    this_album = []
    # TODO(trow): Select the albums to import in a saner way.
    for vol, import_timestamp in sql_db.get_all_imports():
        if start_timestamp is not None and import_timestamp < start_timestamp:
            continue
        cprint("***")
        cprint("*** import_timestamp = %s" % timestamp.get_human_readable(
            import_timestamp))
        cprint("***")
        for au_file in sql_db.get_by_import(vol, import_timestamp):
            if this_album and this_album[0].album_id != au_file.album_id:
                alb = album.Album(this_album)
                pending_albums.append(alb)
                cprint('Adding "%s"' % alb.title())
                pending_albums = maybe_flush(pending_albums)
                this_album = []
            this_album.append(au_file)
            yield

    # Add the last album to the list of pending albums, then do the
    # final flush.
    if this_album:
        alb = album.Album(this_album)
        cprint('Adding "%s"' % alb.title())
        pending_albums.append(alb)
        this_album = []
    flush(pending_albums)

if __name__ == "__main__":
    main()


import lungc
import os.path
import cv2
import random
import numpy as np

nocanc=[]
nocanc_output =[]
for i in range(1,139):#without folder #run for full data
	if not os.path.isfile('without/nocanc ('+str(i)+').jpg'):
		continue
	print(i)
	img=cv2.imread('without/nocanc ('+str(i)+').jpg',0)
	left_feature,right_feature,img_left,img_right=lungc.process_lung(img)

	nocanc.append(left_feature)
	nocanc_output.append(0)

cancl=[]
cancl_output =[]
for i in range(1,121):#left folder #run for full data
	if not os.path.isfile('Left/canc ('+str(i)+').jpg'):
		continue
	print(i)
	img=cv2.imread('Left/canc ('+str(i)+').jpg',0)
	left_feature,right_feature,img_left,img_right=lungc.process_lung(img)

	cancl.append(left_feature)
	cancl_output.append(1)

random.seed(2)
dataset=cancl+nocanc
dataset_output = cancl_output + nocanc_output
random.shuffle(dataset)
random.shuffle(dataset_output)

with open('datafile.py', 'w') as f:
	f.write('dataset = %s' % dataset)
	f.write('\ndataset = %s' % dataset_output)


from django import forms
from .models import Perro, Atencion, Tipo_atencion
from django.utils.encoding import force_str

#Unifico los forms edicion y registro porque eran iguales
class perro_form(forms.ModelForm):
    class Meta:
        model = Perro
        fields = ['nombre', 'raza', 'tamanio', 'sexo', 'fecha_nac', 'color', 'foto']

class editar_foto_form(forms.ModelForm):
    class Meta:
        model = Perro
        fields = ['foto']

class registrar_atencion_form(forms.ModelForm):
    class Meta:
        model = Atencion
        fields = ['tipo', 'peso', 'observacion']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['tipo'].label = "Tipo*"
        self.fields['tipo'].queryset = Tipo_atencion.objects.all()
        self.fields['peso'].label = "Peso*"
        self.fields['observacion'].label = force_str('Observación*')
        self.fields['observacion'].widget.attrs.update({"rows": 3})


#
# Import the libraries we will need for analysis and plotting.
#
import rjmcmc
import matplotlib
import matplotlib.pyplot
from mpl_toolkits.mplot3d import axes3d, Axes3D

#
# Open our data file which consists of one (x, y) coordinater per line
# separated by whitespace
#
f = open('data.txt', 'r')
lines = f.readlines()

x = []
y = []

for line in lines:
    columns = line.split()

    x.append(float(columns[0]))
    y.append(float(columns[1]))

f.close()

#
# Estimate our error standard deviation
#
sigma = 3.0
n = [sigma] * len(x)

#
# Create the rjmcmc dataset
#
data = rjmcmc.dataset1d(x, y, n)

#
# This is our callback function which samples the curves generated
# during the analysis
#
sample_x = None
sample_curves = []
sample_i = 0
sample_rate = 5
def sampler_cb(x, y):
    global sample_x, sample_curves, sample_i, sample_rate

    if sample_i == 0:
        sample_x = x

    if sample_i % sample_rate == 0:
        sample_curves.append(y)

    sample_i = sample_i + 1

#
# Run a series of analyses with varying maximum allowed order
#
results = []
burnin = 100
total = 1000
maxorder = 5
results = rjmcmc.regression_single1d_sampled(data,
                                             sampler_cb,
                                             burnin,
                                             total,
                                             maxorder)

#
# Plot the data with black crosses, the sample curves as faint lines, and
# the mean as a red line
#
fig = matplotlib.pyplot.figure()
ax = fig.add_subplot(111)

yc = 0.5
yalpha = 1.0/((1.0 - yc) * float(len(sample_curves)))
for sy in sample_curves:

    ax.plot(sample_x, sy,
            color = str(yc),
            alpha = yalpha,
            linestyle = '-',
            linewidth = 10)

ax.plot(results.x(), results.mean(), 'r-')
ax.plot(x, y, 'ko')
fig.savefig('ch4-confidence.pdf', format='PDF')

matplotlib.pyplot.show()