Sponsored By
















 

RSS를 가져와서 정리 하는 방법임.

 

 

 

 

실제로 코드를 만들 때에는 이해하면서 왔다갔다 해야하지만 설명이 힘드므로 완성코드만 올릴테니 순서상관없이 붙여넣기하기.

 

 

 

 

 

 

00. 화면구성을 다음과 같이 한다.

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context="com.example.joey.myhttp.MainActivity">

    <EditText

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="http://www.chosun.com/site/data/rss/sports.xml"

        android:id="@+id/editText"

        android:layout_alignParentTop="true"

        android:layout_alignParentLeft="true"

        android:layout_alignParentStart="true"

        android:layout_toLeftOf="@+id/button"

        android:layout_toStartOf="@+id/button"

        android:layout_above="@+id/scrollView" />

    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="RSS 가져오기"

        android:id="@+id/button"

        android:layout_alignParentRight="true"

        android:layout_alignParentEnd="true"

        android:onClick="button01"

        android:layout_alignParentTop="true" />

    <ScrollView

        android:layout_width="match_parent"

        android:layout_height="140dp"

        android:text="New Text"

        android:background="#ffeeddcc"

        android:layout_centerHorizontal="true"

        android:layout_below="@+id/button"

        android:id="@+id/scrollView">

        <TextView

            android:id="@+id/textView2"

            android:layout_width="match_parent"

            android:layout_height="match_parent" />

    </ScrollView>

    <ListView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/listView" />

</RelativeLayout>







01. 자바위에 마우스오른쪽버튼 -> New -> JavaClass 클릭하여 새로운 클래스를 만든다.







02. RssItem 이라고 만들고 OK.







03. 내용을 채워보자.

package com.example.joey.myrss;

public class RssItem {

    String title;

    String link;

    String description;

    String image;

    String dcDate;

 

    public RssItem(){ //생성자

    }

    public RssItem(String title, String link, String description, String image, String dcDate){

        this.title = title;

        this.link = link;

        this.description = description;

        this.image = image;

        this.dcDate = dcDate;

    }

 

/* Getter and Setter 를 이용 */

 

    public String getDcDate() {

        return dcDate;

    }

    public void setDcDate(String dcDate) {

        this.dcDate = dcDate;

    }

    public String getDescription() {

        return description;

    }

    public void setDescription(String description) {

        this.description = description;

    }

    public String getImage() {

        return image;

    }

    public void setImage(String image) {

        this.image = image;

    }

    public String getLink() {

        return link;

    }

    public void setLink(String link) {

        this.link = link;

    }

    public String getTitle() {

        return title;

    }

    public void setTitle(String title) {

        this.title = title;

    }

}







04. 메인스크립트를 입력해보자.

package com.example.joey.myrss;

import android.os.Bundle;

import android.os.Handler;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.EditText;

import android.widget.TextView;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

 

public class MainActivity extends AppCompatActivity {

 

    EditText editText;

    TextView textView;

    Handler handler = new Handler();

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        editText = (EditText) findViewById(R.id.editText);

        textView = (TextView) findViewById(R.id.textView2);

    }

 

    public void button01(View v) {

        RequestThread thread = new RequestThread();

        thread.start();

    }

 

    class RequestThread extends Thread {

        public void run() {

            try {

                String urlStr = editText.getText().toString();

                println("요청 URL : " + urlStr);

 

                URL url = new URL(urlStr);

                HttpURLConnection urconn = (HttpURLConnection) url.openConnection();

                urconn.setDoInput(true);

                urconn.setDoOutput(true);

                urconn.setConnectTimeout(15000); // 15초

 

                int resCode = urconn.getResponseCode();

                println("응답 코드 : " + resCode);

                if (resCode == HttpURLConnection.HTTP_OK) {

                    InputStream instream = urconn.getInputStream();

                    parseRss(instream);

                }

            } catch (Exception e) {

                e.printStackTrace();

            }

        }

    }

 

    private void parseRss(InputStream instream)

            throws Exception {

        println("parseRSS() 호출됨");

 

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        DocumentBuilder builder = factory.newDocumentBuilder();

 

        Document document = builder.parse(instream);

        ArrayList<RssItem> itemList = parseDocument(document);

        println("파싱된 아이템의 갯수 : " + itemList.size());

 

    }

    private ArrayList<RssItem> parseDocument(Document document) {

        Element elem = document.getDocumentElement();

        NodeList nodeList = elem.getElementsByTagName("item");

 

        ArrayList<RssItem> itemList = new ArrayList<RssItem>();

        if (nodeList != null) {

            for (int i = 0; i < nodeList.getLength(); i++) {

                RssItem item = parseItemNode(nodeList, i);

                itemList.add(item);

            }

        }

        return itemList;

    }

    private RssItem parseItemNode(NodeList nodeList, int index) {

        Element elem = (Element) nodeList.item(index);

        Element titleElem = (Element) elem.getElementsByTagName("title").item(0);

        Element linkElem = (Element) elem.getElementsByTagName("link").item(0);

        Element descriptionElem = (Element) elem.getElementsByTagName("description").item(0);

        Element imageElem = (Element) elem.getElementsByTagName("image").item(0);

        Element dcdateElem = (Element) elem.getElementsByTagName("dc:date").item(0);

 

        String title = "";

        if (titleElem != null) {

            Node firstChild = titleElem.getFirstChild();

            if (firstChild != null) {

                title = firstChild.getNodeValue();

            }

        }

        String link = "";

        if (linkElem != null) {

            Node firstChild = linkElem.getFirstChild();

            if (firstChild != null) {

                link = firstChild.getNodeValue();

            }

        }

        String description = "";

        if (descriptionElem != null) {

            Node firstChild = descriptionElem.getFirstChild();

            if (firstChild != null) {

                description = firstChild.getNodeValue();

            }

        }

        String image = "";

        if (imageElem != null) {

            Node firstChild = imageElem.getFirstChild();

            if (firstChild != null) {

                image = firstChild.getNodeValue();

            }

        }

        String dcDate = "";

        if (dcdateElem != null) {

            Node firstChild = dcdateElem.getFirstChild();

            if (firstChild != null) {

                dcDate = firstChild.getNodeValue();

            }

        }

 

        //↓ RSSItem JAVA를 만든후 그것을 array를 이용해서 담겠다.

 

        RssItem item = new RssItem(title, link, description, image, dcDate);

 

        return item;

    }

 

    private void println(final String data) {

        handler.post(new Runnable() {

            @Override

            public void run() {

                textView.append(data + "\n");

            }

        });

    }

}







05. 실행시켜서 버튼을 눌러본다.







06. 원하는 값 도출됨을 확인 할 수 있다.

 

 

 

 

 

 

인터넷에 있는 정보들을 HTTP원문 형식으로 가져오는 방법임.

 

 

 

 

 

 

 

00. 플레인텍스트를 만들어주고 원하는 주소값(http://m.naver.com) 을 입력해줌.

 

 

 

 

 

01. 버튼을 만들어줌. 







02. 플레인텍스트를 EditText로 바꿔주고 아래 텍스트뷰를 스크롤뷰로 감싼다.

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context="com.example.joey.myhttp.MainActivity">

 

    <EditText

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="http://m.naver.com"

        android:id="@+id/editText"

        android:layout_alignParentTop="true"

        android:layout_alignParentLeft="true"

        android:layout_alignParentStart="true"

        android:layout_toLeftOf="@+id/button"

        android:layout_toStartOf="@+id/button"

        android:layout_above="@+id/scrollView" />

 

    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Http 가져오기"

        android:id="@+id/button"

        android:layout_alignParentRight="true"

        android:layout_alignParentEnd="true"

        android:onClick="button01"

        android:layout_alignParentTop="true" />

 

    <ScrollView

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:text="New Text"

        android:background="#ffeeddcc"

        android:layout_centerHorizontal="true"

        android:layout_below="@+id/button"

        android:id="@+id/scrollView">

 

        <TextView

            android:id="@+id/textView2"

            android:layout_width="match_parent"

            android:layout_height="match_parent" />

    </ScrollView>

</RelativeLayout>







03. 메인스크립트를 작성해준다. 네트워킹이기때문에 쓰레드 해줘야함.

package com.example.joey.myhttp;

 

import android.os.Bundle;

import android.os.Handler;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.EditText;

import android.widget.TextView;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

 

public class MainActivity extends AppCompatActivity {

 

    EditText editText;

    TextView textView;

    Handler handler = new Handler();

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        editText = (EditText) findViewById(R.id.editText);

        textView = (TextView) findViewById(R.id.textView2);

    }

    public void button01(View v) {

        RequestThread thread = new RequestThread();

        thread.start();

    }

    class RequestThread extends Thread {

        public void run() {

            try {

                String urlStr = editText.getText().toString();

 

                StringBuilder outputBuilder = new StringBuilder();

 

                URL url = new URL(urlStr);

                HttpURLConnection urconn = (HttpURLConnection) url.openConnection();

                urconn.setDoInput(true);

                urconn.setDoOutput(true);

                urconn.setConnectTimeout(15000); // 15초

 

                int resCode = urconn.getResponseCode();

                if (resCode == HttpURLConnection.HTTP_OK) {

                    BufferedReader reader = new BufferedReader(new InputStreamReader(urconn.getInputStream(), "UTF-8"));

 

                    String line = null;

                    while (true) {

                        line = reader.readLine();

                        if (line == null) {

                            break;

                        }

                        outputBuilder.append(line + "\n");

                    }

 

                    reader.close();

                    urconn.disconnect();

                }

                String output = outputBuilder.toString();

                println(output);

 

            } catch (Exception e) {

                e.printStackTrace();

            }

        }

    }

    private void println(final String data) {

        handler.post(new Runnable() {

            @Override

            public void run() {

                textView.append(data + "\n");

            }

        });

    }

}







04. Manifest로 가서 인터넷접근을 허용 해준다. <uses-permission android:name="android.permission.INTERNET" />







05. 실행해본다.







06. 버튼을 눌러 구동시켜보자.







07. 정상적으로 작동됨을 확인 할 수 있다.

 

 

네트워킹 중 가장 기본인 소켓에 관한 내용임.

 

 

 

 

일단 시작전에 네트워킹 관련된것은 반드시 쓰레드 사용과 + 인터넷권한 을 줘야한다는 두가지 전제가 있다.

 

 

내용을 따라가다보면 피시IP주소가 필요한데 내 피시 IP주소 보는법은 링크 참조.

http://blog.naver.com/pandekten5/220622082174

 

 

 

 

 

 

 

 

 

 

00. 역시나 일단 시작해보자.







01. 버튼을 누르면 작동되게 버튼을 만들어보자. 온클릭 속성을 줘서 간단히 해보자.







02. 작업결과를 텍스트뷰에 나타나게 해보자. 하지만 구별되기 위해 색상을 줘보자.







03. Manifest에서 인터넷권한을 주자.







04. 메인스크립에다 메인소스를 주자.

package com.example.joey.mysocket;

import android.os.Bundle;

import android.os.Handler;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.TextView;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.net.Socket;

public class MainActivity extends AppCompatActivity {

    TextView textView;

    Handler handler = new Handler();

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        textView = (TextView) findViewById(R.id.textView);

    }

    public void button01(View v) {

        ConnectThread thread = new ConnectThread();

        thread.start();

    }

    class ConnectThread extends Thread {

        public void run() {

            String host = "172.30.1.4"; //내 피시 IP주소

            int port = 5001;

            try {

                Socket socket = new Socket(host, port);

                println("서버로 연결되었습니다. : " + host + ", " + port);

                String output = "Hello";

 

                ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());

                outputStream.writeObject(output);

                outputStream.flush();

                println("서버로 보낸 데이터 : " + output);

 

                ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());

                Object input = inputStream.readObject();

                println("서버로부터 받은 데이터 : " + input);

 

                inputStream.close();

                outputStream.close();

                socket.close();

 

           } catch (Exception e) {

                e.printStackTrace();

            }

        }

        private void println(final String data){

            handler.post(new Runnable() {

                @Override

                public void run() {

                    textView.append(data + "\n");

                }

            });

        }

    }

}







05. 실행시켜보자.







06. 서버를 만들지 않고 시작해서인지, 텍스트뷰로 나타나지않는다. 

 

 

 

optim {stats}                                                                                  R Documentation

 

General-purpose Optimization

 

 

Description

 

General-purpose optimization based on Nelder–Mead, quasi-Newton and conjugate-gradient algorithms. It includes an option for box-constrained optimization and simulated annealing.

 

 

Usage

 

optim(par, fn, gr = NULL, ...,

      method = c("Nelder-Mead", "BFGS", "CG", "L-BFGS-B", "SANN",

                 "Brent"),

      lower = -Inf, upper = Inf,

      control = list(), hessian = FALSE)

 

optimHess(par, fn, gr = NULL, ..., control = list())

 

 

Arguments

 

par

Initial values for the parameters to be optimized over.

 

fn

A function to be minimized (or maximized), with first argument the vector of parameters over which minimization is to take place. It should return a scalar result.

 

gr

A function to return the gradient for the "BFGS", "CG" and "L-BFGS-B" methods. If it is NULL, a finite-difference approximation will be used.

 

For the "SANN" method it specifies a function to generate a new candidate point. If it is NULL a default Gaussian Markov kernel is used.

 

...

Further arguments to be passed to fn and gr.

 

method

The method to be used. See ‘Details’. Can be abbreviated.

 

lower, upper

Bounds on the variables for the "L-BFGS-B" method, or bounds in which to search for method "Brent".

 

control

A list of control parameters. See ‘Details’.

 

hessian

Logical. Should a numerically differentiated Hessian matrix be returned?

 

 

Details

 

Note that arguments after ... must be matched exactly.

 

By default optim performs minimization, but it will maximize if control$fnscale is negative. optimHess is an auxiliary function to compute the Hessian at a later stage if hessian = TRUE was forgotten.

 

The default method is an implementation of that of Nelder and Mead (1965), that uses only function values and is robust but relatively slow. It will work reasonably well for non-differentiable functions.

 

Method "BFGS" is a quasi-Newton method (also known as a variable metric algorithm), specifically that published simultaneously in 1970 by Broyden, Fletcher, Goldfarb and Shanno. This uses function values and gradients to build up a picture of the surface to be optimized.

 

Method "CG" is a conjugate gradients method based on that by Fletcher and Reeves (1964) (but with the option of Polak–Ribiere or Beale–Sorenson updates). Conjugate gradient methods will generally be more fragile than the BFGS method, but as they do not store a matrix they may be successful in much larger optimization problems.

 

Method "L-BFGS-B" is that of Byrd et. al. (1995) which allows box constraints, that is each variable can be given a lower and/or upper bound. The initial value must satisfy the constraints. This uses a limited-memory modification of the BFGS quasi-Newton method. If non-trivial bounds are supplied, this method will be selected, with a warning.

 

Nocedal and Wright (1999) is a comprehensive reference for the previous three methods.

 

Method "SANN" is by default a variant of simulated annealing given in Belisle (1992). Simulated-annealing belongs to the class of stochastic global optimization methods. It uses only function values but is relatively slow. It will also work for non-differentiable functions. This implementation uses the Metropolis function for the acceptance probability. By default the next candidate point is generated from a Gaussian Markov kernel with scale proportional to the actual temperature. If a function to generate a new candidate point is given, method "SANN" can also be used to solve combinatorial optimization problems. Temperatures are decreased according to the logarithmic cooling schedule as given in Belisle (1992, p. 890); specifically, the temperature is set to temp / log(((t-1) %/% tmax)*tmax + exp(1)), where t is the current iteration step and temp and tmax are specifiable via control, see below. Note that the "SANN" method depends critically on the settings of the control parameters. It is not a general-purpose method but can be very useful in getting to a good value on a very rough surface.

 

Method "Brent" is for one-dimensional problems only, using optimize(). It can be useful in cases where optim() is used inside other functions where only method can be specified, such as in mle from package stats4.

 

Function fn can return NA or Inf if the function cannot be evaluated at the supplied value, but the initial value must have a computable finite value of fn. (Except for method "L-BFGS-B" where the values should always be finite.)

 

optim can be used recursively, and for a single parameter as well as many. It also accepts a zero-length par, and just evaluates the function with that argument.

 

The control argument is a list that can supply any of the following components:

 

trace

Non-negative integer. If positive, tracing information on the progress of the optimization is produced. Higher values may produce more tracing information: for method "L-BFGS-B" there are six levels of tracing. (To understand exactly what these do see the source code: higher levels give more detail.)

 

fnscale

An overall scaling to be applied to the value of fn and gr during optimization. If negative, turns the problem into a maximization problem. Optimization is performed on fn(par)/fnscale.

 

parscale

A vector of scaling values for the parameters. Optimization is performed on par/parscale and these should be comparable in the sense that a unit change in any element produces about a unit change in the scaled value. Not used (nor needed) for method = "Brent".

 

ndeps

A vector of step sizes for the finite-difference approximation to the gradient, on par/parscale scale. Defaults to 1e-3.

 

maxit

The maximum number of iterations. Defaults to 100 for the derivative-based methods, and 500 for "Nelder-Mead".

 

For "SANN" maxit gives the total number of function evaluations: there is no other stopping criterion. Defaults to 10000.

 

abstol

The absolute convergence tolerance. Only useful for non-negative functions, as a tolerance for reaching zero.

 

reltol

Relative convergence tolerance. The algorithm stops if it is unable to reduce the value by a factor of reltol * (abs(val) + reltol) at a step. Defaults to sqrt(.Machine$double.eps), typically about 1e-8.

 

alpha, beta, gamma

Scaling parameters for the "Nelder-Mead" method. alpha is the reflection factor (default 1.0), beta the contraction factor (0.5) and gamma the expansion factor (2.0).

 

REPORT

The frequency of reports for the "BFGS", "L-BFGS-B" and "SANN" methods if control$trace is positive. Defaults to every 10 iterations for "BFGS" and "L-BFGS-B", or every 100 temperatures for "SANN".

 

type

for the conjugate-gradients method. Takes value 1 for the Fletcher–Reeves update, 2 for Polak–Ribiere and 3 for Beale–Sorenson.

 

lmm

is an integer giving the number of BFGS updates retained in the "L-BFGS-B" method, It defaults to 5.

 

factr

controls the convergence of the "L-BFGS-B" method. Convergence occurs when the reduction in the objective is within this factor of the machine tolerance. Default is 1e7, that is a tolerance of about 1e-8.

 

pgtol

helps control the convergence of the "L-BFGS-B" method. It is a tolerance on the projected gradient in the current search direction. This defaults to zero, when the check is suppressed.

 

temp

controls the "SANN" method. It is the starting temperature for the cooling schedule. Defaults to 10.

 

tmax

is the number of function evaluations at each temperature for the "SANN" method. Defaults to 10.

 

Any names given to par will be copied to the vectors passed to fn and gr. Note that no other attributes of par are copied over.

 

The parameter vector passed to fn has special semantics and may be shared between calls: the function should not change or copy it.

 

 

Value

 

For optim, a list with components:

 

par

The best set of parameters found.

 

value

The value of fn corresponding to par.

 

counts

A two-element integer vector giving the number of calls to fn and gr respectively. This excludes those calls needed to compute the Hessian, if requested, and any calls to fn to compute a finite-difference approximation to the gradient.

 

convergence

An integer code. 0 indicates successful completion (which is always the case for "SANN" and "Brent"). Possible error codes are

 

1

indicates that the iteration limit maxit had been reached.

 

10

indicates degeneracy of the Nelder–Mead simplex.

 

51

indicates a warning from the "L-BFGS-B" method; see component message for further details.

 

52

indicates an error from the "L-BFGS-B" method; see component message for further details.

 

message

A character string giving any additional information returned by the optimizer, or NULL.

 

hessian

Only if argument hessian is true. A symmetric matrix giving an estimate of the Hessian at the solution found. Note that this is the Hessian of the unconstrained problem even if the box constraints are active.

 

For optimHess, the description of the hessian component applies.

 

 

Note

 

optim will work with one-dimensional pars, but the default method does not work well (and will warn). Method "Brent" uses optimize and needs bounds to be available; "BFGS" often works well enough if not.

 

 

Source

 

The code for methods "Nelder-Mead", "BFGS" and "CG" was based originally on Pascal code in Nash (1990) that was translated by p2c and then hand-optimized. Dr Nash has agreed that the code can be made freely available.

 

The code for method "L-BFGS-B" is based on Fortran code by Zhu, Byrd, Lu-Chen and Nocedal obtained from Netlib (file ‘opt/lbfgs_bcm.shar’: another version is in ‘toms/778’).

 

The code for method "SANN" was contributed by A. Trapletti.

 

 

References

 

Belisle, C. J. P. (1992) Convergence theorems for a class of simulated annealing algorithms on Rd. J. Applied Probability, 29, 885–895.

 

Byrd, R. H., Lu, P., Nocedal, J. and Zhu, C. (1995) A limited memory algorithm for bound constrained optimization. SIAM J. Scientific Computing, 16, 1190–1208.

 

Fletcher, R. and Reeves, C. M. (1964) Function minimization by conjugate gradients. Computer Journal 7, 148–154.

 

Nash, J. C. (1990) Compact Numerical Methods for Computers. Linear Algebra and Function Minimisation. Adam Hilger.

 

Nelder, J. A. and Mead, R. (1965) A simplex algorithm for function minimization. Computer Journal 7, 308–313.

 

Nocedal, J. and Wright, S. J. (1999) Numerical Optimization. Springer.

 

See Also

 

nlm, nlminb.

 

optimize for one-dimensional minimization and constrOptim for constrained optimization.

 

 

Examples

 

require(graphics)

 

fr <- function(x) {   ## Rosenbrock Banana function

    x1 <- x[1]

    x2 <- x[2]

    100 * (x2 - x1 * x1)^2 + (1 - x1)^2

}

grr <- function(x) { ## Gradient of 'fr'

    x1 <- x[1]

    x2 <- x[2]

    c(-400 * x1 * (x2 - x1 * x1) - 2 * (1 - x1),

       200 *      (x2 - x1 * x1))

}

optim(c(-1.2,1), fr)

(res <- optim(c(-1.2,1), fr, grr, method = "BFGS"))

optimHess(res$par, fr, grr)

optim(c(-1.2,1), fr, NULL, method = "BFGS", hessian = TRUE)

## These do not converge in the default number of steps

optim(c(-1.2,1), fr, grr, method = "CG")

optim(c(-1.2,1), fr, grr, method = "CG", control = list(type = 2))

optim(c(-1.2,1), fr, grr, method = "L-BFGS-B")

 

flb <- function(x)

    { p <- length(x); sum(c(1, rep(4, p-1)) * (x - c(1, x[-p])^2)^2) }

## 25-dimensional box constrained

optim(rep(3, 25), flb, NULL, method = "L-BFGS-B",

      lower = rep(2, 25), upper = rep(4, 25)) # par[24] is *not* at boundary

 

## "wild" function , global minimum at about -15.81515

fw <- function (x)

    10*sin(0.3*x)*sin(1.3*x^2) + 0.00001*x^4 + 0.2*x+80

plot(fw, -50, 50, n = 1000, main = "optim() minimising 'wild function'")

 

res <- optim(50, fw, method = "SANN",

             control = list(maxit = 20000, temp = 20, parscale = 20))

res

## Now improve locally {typically only by a small bit}:

(r2 <- optim(res$par, fw, method = "BFGS"))

points(r2$par, r2$value, pch = 8, col = "red", cex = 2)

 

## Combinatorial optimization: Traveling salesman problem

library(stats) # normally loaded

 

eurodistmat <- as.matrix(eurodist)

 

distance <- function(sq) {  # Target function

    sq2 <- embed(sq, 2)

    sum(eurodistmat[cbind(sq2[,2], sq2[,1])])

}

 

genseq <- function(sq) {  # Generate new candidate sequence

    idx <- seq(2, NROW(eurodistmat)-1)

    changepoints <- sample(idx, size = 2, replace = FALSE)

    tmp <- sq[changepoints[1]]

    sq[changepoints[1]] <- sq[changepoints[2]]

    sq[changepoints[2]] <- tmp

    sq

}

 

sq <- c(1:nrow(eurodistmat), 1)  # Initial sequence: alphabetic

distance(sq)

# rotate for conventional orientation

loc <- -cmdscale(eurodist, add = TRUE)$points

x <- loc[,1]; y <- loc[,2]

s <- seq_len(nrow(eurodistmat))

tspinit <- loc[sq,]

 

plot(x, y, type = "n", asp = 1, xlab = "", ylab = "",

     main = "initial solution of traveling salesman problem", axes = FALSE)

arrows(tspinit[s,1], tspinit[s,2], tspinit[s+1,1], tspinit[s+1,2],

       angle = 10, col = "green")

text(x, y, labels(eurodist), cex = 0.8)

 

set.seed(123) # chosen to get a good soln relatively quickly

res <- optim(sq, distance, genseq, method = "SANN",

             control = list(maxit = 30000, temp = 2000, trace = TRUE,

                            REPORT = 500))

res  # Near optimum distance around 12842

 

tspres <- loc[res$par,]

plot(x, y, type = "n", asp = 1, xlab = "", ylab = "",

     main = "optim() 'solving' traveling salesman problem", axes = FALSE)

arrows(tspres[s,1], tspres[s,2], tspres[s+1,1], tspres[s+1,2],

       angle = 10, col = "red")

text(x, y, labels(eurodist), cex = 0.8)

 

 

 

 

※. Reference :

http://stat.ethz.ch/R-manual/R-devel/library/stats/html/optim.html

 

 

 

 

 

 

 

1. 이클립스와 R 설치

 

 

2. R> install.packages("rJave")

 

 

3. PATH 값 설정 (본인의 폴더위치로 각자 수정)

1) JAVA_HOME

;C:\Program Files\Java\jdk1.8.0_65

2) R_HOME

D:\Program Files\R\R-3.3.1

3) PATH

;C:\Program Files\Java\jdk1.8.0_65\lib\tools.jar;%JAVA_HOME%\bin;%R_HOME%\bin\i386;%R_HOME%\library\rJava\jri\i386;

 

 

4. Eclipse 내 프로젝트 오른쪽 마우스 클릭

-> Run As -> Run Configurations...

-> arguments 탭에서 

-Djava.library.path=D:\Program Files\R\R-3.3.1\library\rJava\jri\i386

   environment 탭에서 

LD_LIBRARY_PATH

D:\Program Files\R\R-3.3.1\bin;D:\Program Files\R\R-3.3.1\library;

PATH

D:\Program Files\R\R-3.3.1\bin\i386;D:\Program Files\R\R-3.3.1\library\rJava\jri\i386

R_HOME

D:\Program Files\R\R-3.3.1

 

 

5. D:\Program Files\R\R-3.3.1\library\rJava\jri 내에 위치한 JRI.jar 파일을 임포트시킨다.

-> 이클립스내 Windows-> Properties-> Java Build Path -> Libraries(탭) -> Add External JARs ->D:\Program Files\R\R-3.3.1\library\rJava\jri 내에 있는 JRI.jar 선택.

 

 

6. C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext 내에 JRI.jar 를 복사해준다.

 

 

 

※. /i386 과 /x64 내에 같은 파일이 들어있으므로 어느것으로 해도 무방하다.

 

 

 

 

 

 

 

 

 



Sponsored By















+ Recent posts