[카테고리:] 컴퓨터

  • 광섬유 가공 후 데이터를 자동으로 분석하는 프로그램

    #!/usr/bin/env python

    # -*- coding: CP949 -*-

    #

    # generated by wxGlade 0.7.2 on Tue Apr 05 01:49:01 2016

    #

    # This is a converting program from thorlabs powermeter datafile taken from thorlab official data acquisition program to radius vs power after fiber taper process.

    # IF you want to use this program for your own purpose except learning python and programming, you have to ask me licence policy and copyright.

    # snowall@kaist.ac.kr / snowall@gmail.com / Keehwan Nam, Physics department, KAIST. 2016.

    #

    import wx

    # begin wxGlade: dependencies

    import gettext

    # end wxGlade

    # begin wxGlade: extracode

    # end wxGlade

    import numpy as np

    import os

    import re

    import sys

    import struct

    f= open(‘sample.png’, ‘rb’)

    w, h = struct.unpack(‘>LL’, f.read()[16:24])

    displaysizeX = int(w)

    displaysizeY = int(h)

    f.close()

    reload(sys)

    sys.setdefaultencoding(‘cp949’)

    #~ displaysizeX=1280

    #~ displaysizeY=1024

    x,y=0,0

    a=0

    b=0

    c=0

    sec=0

    minute=0

    hours=0

    msec=0

    class MyDialog(wx.Dialog):

    x00=0

    y00=0

    def __init__(self, parent, id, title):

    wx.Dialog.__init__(self, parent, id, title, size=(displaysizeX,displaysizeY))

    self.canvas = wx.StaticBitmap(self, -1, wx.Bitmap(“sample.png”, wx.BITMAP_TYPE_ANY))

    self.canvas.Bind(wx.EVT_LEFT_DOWN, self.positionnow)

    def positionnow(self, event):

    self.x00=wx.MouseEvent.GetX(event)

    self.y00=wx.MouseEvent.GetY(event)

    print((wx.MouseEvent.GetX(event),wx.MouseEvent.GetY(event)))

    def drawTick(self, pl):

    self.mydc = wx.MemoryDC()

    self.canvas2 = wx.Bitmap(“sample.png”, wx.BITMAP_TYPE_ANY)

    self.mydc.SelectObject(self.canvas2)

    self.mypen=wx.Pen(wx.Colour(255,0,0),5)

    self.mypen.SetWidth(1)

    self.mydc.SetPen(self.mypen)

    self.mydc.DrawLines(pl)

    self.mydc.SelectObject(wx.NullBitmap)

    self.canvas.SetBitmap(self.canvas2)

    self.mydc = None

    self.canvas = wx.StaticBitmap(self, -1, self.canvas2)

    return

    def graphroutine(self, myf):

    self.convertedData=[]

    self.pointlist=[]

    src=open(myf, “r”)

    src.readline()

    d=src.readline()

    a=d.split(” “)

    self.mini=np.inf

    self.maxi=0.

    while True:

    d=src.readline()

    if d==””:

    break

    a=d.split(” “)

    msec=float(((a[1]).split(“.”))[1])*0.001

    sec=float(a[2].split(“:”)[2].split(“\t”)[0])

    minute=float((a[2]).split(“:”)[1])*60.

    hours=float((a[2]).split(“:”)[0])*3600.

    self.time=msec+sec+minute+hours

    self.convertedData+=[[self.time,float(a[2].split(“:”)[2].split(“\t”)[1])]]

    if self.convertedData[-1][1] self.mini=self.convertedData[-1][1]

    if self.convertedData[-1][1]>self.maxi:

    self.maxi=self.convertedData[-1][1]

    self.time0=self.convertedData[0][0]

    self.time1=self.convertedData[-1][0]

    self.timescale=displaysizeX/(self.time1-self.time0)

    self.vertscale=displaysizeY/(self.maxi-self.mini)

    for cd in self.convertedData:

    self.pointlist+=[[np.ceil((cd[0]-self.time0)*self.timescale),displaysizeY-np.ceil((cd[1]-self.mini)*self.vertscale)]]

    self.drawTick(self.pointlist)

    src.flush()

    src.close()

    return

    def findV(self,no):

    logfile=open(“log.csv”,”r”)

    try:

    while True:

    d=logfile.readline()

    if d==””:

    break

    a=d.split(“,”)

    if a[0]==str(no):

    logfile.close()

    return a

    except:

    logfile.close()

    return “0”

    def inverse_ratio(self,logdata):

    return np.sqrt(((2.*float(logdata[15]))-float(logdata[14]))/((2.*float(logdata[15]))+float(logdata[14])))

    def converting(self,f):

    self.time0=(self.x00/self.timescale)+self.time0

    tar=open(f[:-4]+”_processed.txt”, “w”)

    errorlist=open(“errorlist.txt”,”a”)

    plot=open(f[:-4]+”.gpl”, “w”)

    shotnumber=re.search(“\d+”,f.split(“\\”)[-1]).group()

    expcondition=self.findV(shotnumber)

    shotlog=self.inverse_ratio(expcondition)

    try:

    for cd in self.convertedData:

    tar.writelines(str(cd[0])+”\t”+str(cd[1])+”\t”+str(float(expcondition[9])*np.power(shotlog,(cd[0]-self.time0)/(float(expcondition[11])/float(expcondition[15]))))+”\t”+str(cd[1])+”\n”)

    plot.writelines(“set logscale x\nplot \””+(f.split(“\\”)[-1])[:-4]+”_processed.txt\” using 3:4 w l “)

    except:

    errorlist.writelines(f+”\n”)

    print “error”

    finally:

    tar.flush()

    tar.close()

    plot.flush()

    plot.close()

    class MainPlotFrame(wx.Frame):

    def __init__(self, *args, **kwds):

    # begin wxGlade: MainPlotFrame.__init__

    kwds[“style”] = wx.DEFAULT_FRAME_STYLE

    wx.Frame.__init__(self, *args, **kwds)

    self.dig = wx.FileDialog(None, message=”Choose data files”, style = wx.FD_MULTIPLE)

    self.dia = MyDialog(self, -1, ‘Close after click!’)

    self.__set_properties()

    self.__do_layout()

    if self.dig.ShowModal() == wx.ID_OK:

    for fn in self.dig.GetPaths():

    self.dia.graphroutine(fn)

    self.dia.ShowModal()

    self.dia.converting(fn)

    self.Close()

    # end wxGlade

    def __set_properties(self):

    # begin wxGlade: MainPlotFrame.__set_properties

    self.SetTitle((“frame_1”))

    self.SetSize((displaysizeX, displaysizeY))

    # end wxGlade

    def __do_layout(self):

    # begin wxGlade: MainPlotFrame.__do_layout

    sizer_1 = wx.BoxSizer(wx.VERTICAL)

    self.SetSizer(sizer_1)

    self.Layout()

    # end wxGlade

    # end of class MainPlotFrame

    if __name__ == “__main__”:

    app = wx.App(0)

    #~ wx.InitAllImageHandlers()

    frame_main = MainPlotFrame(None, -1, “”)

    frame_main.Show()

    app.MainLoop()

  • 윈도우에 선 긋는 파이썬 예제

    #!/usr/bin/env python

    # -*- coding: CP949 -*-

    #

    # generated by wxGlade 0.7.2 on Tue Apr 05 01:49:01 2016

    #

    import wx

    # begin wxGlade: dependencies

    import gettext

    # end wxGlade

    # begin wxGlade: extracode

    # end wxGlade

    class MainPlotFrame(wx.Frame):

    canvas = 1

    x00=0

    y00=0

    def __init__(self, *args, **kwds):

    # begin wxGlade: MainPlotFrame.__init__

    kwds[“style”] = wx.DEFAULT_FRAME_STYLE

    wx.Frame.__init__(self, *args, **kwds)

    self.canvas = wx.StaticBitmap(self, -1, wx.Bitmap(“sample.png”, wx.BITMAP_TYPE_ANY))

    self.canvas.Bind(wx.EVT_LEFT_DOWN, self.positionnow)

    self.__set_properties()

    self.__do_layout()

    # end wxGlade

    def __set_properties(self):

    # begin wxGlade: MainPlotFrame.__set_properties

    self.SetTitle((“frame_1”))

    self.SetSize((1024, 768))

    # end wxGlade

    def __do_layout(self):

    # begin wxGlade: MainPlotFrame.__do_layout

    sizer_1 = wx.BoxSizer(wx.VERTICAL)

    self.SetSizer(sizer_1)

    self.Layout()

    # end wxGlade

    def positionnow(self, event):

    self.x00=wx.MouseEvent.GetX(event)

    self.y00=wx.MouseEvent.GetY(event)

    print((wx.MouseEvent.GetX(event),wx.MouseEvent.GetY(event)))

    self.drawTick(self.x00,self.y00,self.x00+100,self.y00-30)

    def drawTick(self, x0, y0, x1, y1):

    self.mydc = wx.MemoryDC()

    frame_main.canvas2 = wx.Bitmap(“sample.png”, wx.BITMAP_TYPE_ANY)

    self.mydc.SelectObject(self.canvas2)

    self.mydc.SetPen(wx.Pen(self.colorDecision(),1))

    self.mydc.DrawLine(x0, y0, x1, y1)

    self.mydc.SelectObject(wx.NullBitmap)

    self.canvas.SetBitmap(self.canvas2)

    self.mydc = None

    self.canvas = wx.StaticBitmap(self, -1, self.canvas2)

    return 0

    def colorDecision(self):

    return wx.Colour(255, 0,0)

    # end of class MainPlotFrame

    # end of class MainPlotFrame

    if __name__ == “__main__”:

    app = wx.App(0)

    #~ wx.InitAllImageHandlers()

    frame_main = MainPlotFrame(None, -1, “”)

    frame_main.Show()

    app.MainLoop()

    언젠가는 써먹겠지…

  • 알파고

    알파고가 변칙적인 수를 두어서 이세돌을 이겼다고 하는데, 사실 여기서 오해하면 안되는 것이 있다. 알파고가 학습한 기보에서 이런 변칙적인 수가 등장한 경우가 있었을 것이고, 그런 수가 승리한 경우가 있었을 것이다. 이런 수를 학습하면 (그 수가 어떤 의미인지 모르더라도) 변칙적인 수를 두어서 승리할 수 있다. (중국어 방 문제를 생각해 보자.) 기보 학습 없이 기존의 고전적인 알고리즘으로 두었다면 아무리 빵빵한 알고리즘과 연산성능의 지원을 받더라도 알파고는 실수로 여겨지는 변칙적인 수를 둘 수 없었을 것이다.

    현 시대의 인공지능은 일단 ‘흉내내기’ 차원에서는 많이 발달하였다. 울프람 알파, 신문기사 자동 작성, 아이폰 시리, 구글 자동운전차 등등. 문장을 분석해서 인간이 이해하는 의미를 찾아내고, 인간이 원하는 행동을 한다. 하지만 인간이 이해한 그 의미가 어떤 의미인지 직접 이해하지는 못한다. 추상적인 단계에서 인간이 이해하는 의미에 어떤 수치 또는 벡터를 만들고, 결과물이 그와 같은 벡터를 향하도록 수행하는 것이다. 이 벡터가 입력과 출력에 대해서 같으므로 인공지능이 수행한 결과물은 인간이 원하는 결과가 된다.

    내 생각에 알파고는 바둑 잘 두는 기계지 ‘인공지능’의 레벨에는 아직 도달하지 못했다. (적어도 강한 의미의 인공지능은 아니다.)

    기계가 인간을 따라잡으려면 내가 보기엔 100년은 더 걸릴텐데 다들 괜히 설레발 치는 것 같아서 참 안타깝다.

    그보다, 인공지능으로 사람들이 일자리를 잃을 걱정을 하지 말고, 인공지능으로 절약한 인건비를 복지로 돌려서 먹고살 수 있는 세상을 만드는게 더 중요하다. 물론 우리나라같은 추세로 가면 한 200년쯤 후에는 기계밖에 안 남아있겠지.

  • 서버 관리용

    내가 관리하는 서버가 죽으면 나에게 이메일을 보내주는 스크립트. 물론 이 스크립트는 관리하는 서버가 아닌 다른 서버에서 cron을 이용해서 정해진 시간간격으로 실행된다.

    #!/bin/bash

    if wget your.domain.com

    then

    rm index.html

    else

    echo “helo melotopia

    mail from: your@emailaddress.com

    rcpt to: your@emailaddress.com

    data

    server should be down. Correct it!

    .

    quit” | telnet localhost 25

    fi

    물론 sendmail이 서버에 설정되어 있고 데몬이 돌아가고 있어야 한다.

    sendmail 보안이 좀 걱정스럽지만 localhost에서만 보내도록 설정했으니 뭐 별일 있겠나…

  • 위에서 아래로 채워주는 VBA

    엑셀 VBA는 프로그래밍 언어인지 매크로인지 잘 모르겠지만, 강력하긴 하다.

    Sub copyandpast()

    i = 5

    Do While i < 400
    For j = 2 To 23

    If Cells(i, j).Value = “” Then

    Cells(i, j).Value = Cells(i – 1, j).Value

    End If

    Next j

    i = i + 1

    Loop

    End Sub

    이 코드는 다음줄이 빈칸이면 그 윗줄에서 찾아다가 채워주는 코드이다. 즉, 파일이 빈칸없이 채워진다.

    실제 사용시에는 저기 5, 400, 2, 23과 같은 숫자들을 고쳐서 쓰면 된다.

  • 파이썬의 for문과 배열 처리

    파이썬의 반복구문인 for는 배열을 처리하는데 매우 간단한 방법을 제공한다. 가령, ar이라는 배열이 이미 선언되어 있으면, ar의 원소들을 하나하나 끌어서 처리하는데 다음과 같이 쓰면 된다.

    for i in ar:

    myFunction(i)

    문제는 내가 i가 몇번째 원소인지 굳이 알아야만 하는 경우에 나타난다. 내가 지금 푸는 문제는 전체 길이가 N인 배열에서 k번째 원소와 k+m번째 원소 사이에 있는 원소에만 함수를 적용해야 하는 상황이기 ‹š문에 굳이 필요하다. 이 경우, 고전적인 방법으로

    for i in range(len(ar)):

    if i>k and i

    myFunction(ar[i])

    이렇게 쓰면 될 것이다. 또는

    j=0

    for i in ar:

    if j>k and j

    myFunction(ar)

    j+=1

    이렇게 쓸 수도 있다. 하지만 이렇게 작성하는 것은 전혀 파이썬스러운 코딩이 아니다. 파이썬처럼 코딩하는 것은 제일 처음에 쓴 바로 그것이다. 그래서 지금 어떻게 하고 있냐고?

    myFunction(ar[k:k+m])

    이렇게 해보고 있다. 뭔가 이상하지만 이제 파이썬 스러워졌다.

  • 병신코드

    누가 봐도 오타를 낸 것 같아 보이겠지만 의도한 대로 작동하는 코드를 만들었다. 어쩌다보니 어떤 변수 i가 가장 처음엔 0에서 시작하는데 두번째부터 1로 고정되는 루틴을 만들어야 했는데, 조건문을 쓰고싶지 않았다. 그래서..

    i=0

    while True:

    myFunction(x, i)

    i=1

    파이썬 스타일 코딩이다.

    이런식으로 만들었다. 보통 저 자리에 i=1이 아니라 i+=1을 넣기 때문에 오타같아 보이지만, 사실은 의도한대로 잘 적은 것이다. 이 기록은 나중에 내가 까먹고 저걸 디버깅(!) 해 버릴까봐 작성해 둔다. 물론 저 코드에는 따로 주석도 달아두었다.

  • 배워본 언어들

    C언어 – 읽기 어렵다. 컴파일해야 실행시켜볼 수 있다. 잘 짜면 빠르긴 한데 초보한텐 그게 그거라는게 함정.

    파이썬 – C언어보다는 읽기 쉽다. 처음에 배우기 쉽다. 다른 사람한테 프로그램 전달할 때 패키징하는게 골때린다.

    랩뷰 – 입으로 코딩하고 싶은 1순위 언어.

    매스매티카 – 리습의 영향을 받아서 그런가, 괄호에 미친언어. C언어같은 절차형 프로그래밍 언어를 먼저 배우고서 매스매티카를 배우려면 뭔가 혼란이 올 수 있다.

    매트랩 – 이상한 문법을 쓰는 행렬용 계산기. 자의로 쓰고싶지는 않은 언어다.

    비주얼베이직 – ‘이게 왜 작동하지?’싶은 수준의 코드도 굴러간다. 윈도우 전용인게 단점. 그리고 프로그램 만드는 것 자체는 VS의 도움을 받아서 어렵지 않은데, 완성된 코드를 보면 복잡하다.

    메이플 – 느리다. 쓰지 마라.

  • 그래프 따는 프로그램


    http://digitizer.sourceforge.net/

    This open source, digitizing software converts an image file showing a graph or map, into numbers. The image file can come from a scanner, digital camera or screenshot. The numbers can be read on the screen, and written or copied to a spreadsheet.

    The process starts with an image file containing a graph or map. You add three axis points to define the axes, then other points along your curve(s).The final result is digitized data that can be used by other tools such as Microsoft Excel and Gnumeric.

    Engauge (from en “make” and gauge “to measure”) verb meaning to convert an image file containing a graph or map, into numbers.

    The term “Engauge” in Engauge Digitizer was invented for this project, since there seems to be no similar term in common use.

    Why Would You Need This Tool?

    Here are some real-life examples:

    You are an engineer with some graphs in decades-old documents, but you really need the numbers represented in those graphs so you can do analyses that will determine if a space vehicle is safe to fly.

    You are a graduate student gathering historical data from charts for your thesis.

    You are a webmaster with visitor statistics charts and you want to do statistical analyses.

    You ride a bike or boat and want to know how much distance you covered in your last trip, but you do not have an odometer or GPS unit. However, you do have a map.

    Nice Features

    Automatic curve tracing of line plots

    Automatic point matching of point plots

    Automatic axes matching

    Automatic grid line removal for improved curve tracing

    Handles cartesian, polar, linear and logarithmic graphs

    Support for drag-and-drop and copy-and-paste makes data transfer fast and easy

    Image processing tools highlight data by removing grid lines and backgrounds

    Status bar suggestions guide beginners

    Context sensitive popup help windows reveal explain feature of the user interface

    Tutorials with pictures explain strategies for common operations

    Browser-based user manual is extensive yet easy to navigate

    Preview windows give immediate feedback while modifying settings

    Dates and times are imported with the Date/Time Converter

    Import support for common image file formats such as BMP, GIF, JPEG, PNG and XPM

    Export support for common software packages such as Microsoft Excel, OpenOffice CALC, gnuplot, gnumeric, MATLAB and Mathematica

    Engauge is available for a wide variety of platforms (Linux, Mac OSX, Windows)

    Engauge Digitizer is completely open source and free courtesy of Sourceforge, Github, Digia and FFTW

    좋아보인다. 언제고 쓸일이 있을듯.

  • 방금 그거

    뭐에 쓰는 프로그램인지는 방금 그거.

    사용법

    라인 수 = 입력하면 해당 라인 마다 파일 하나씩 만들어준다

    숫자 2개 = 두 칼럼을 교체한다. 둘 중 하나가 0이면 0이 아닌쪽의 칼럼은 사라진다. 둘 다 같거나 둘 다 0이면 아무일 없음.




    csv_split.zip




    csv_split.exe

    저작권은 물론 내꺼.

    VS2013으로 개발했음. 닷넷3.0이상 필요한듯.