一般随机游走发电机问题

时间:2015-04-27 02:26:13

标签: python random-walk

好吧所以我有一些关于如何继续我的python脚本以生成一组随机漫步的一般性问题。到目前为止,我在我的程序中有一个单步的随机游走,工作正常。我的问题是,我想创建一个for循环,以使其成为多个助行器,假设20由程序处理。我该怎么做呢?另外,我试图找到每个步行者的位移均方根值。我不知道该怎么做,我只知道我需要找到总位移和每个步长平方之间所有差异的总和,然后除以步骤总数,但我不确定编码也是如此。任何帮助将不胜感激,谢谢! 这是我到目前为止的代码

package com.example.httpclient;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;

public class Main extends Activity {//originally named GetPrayerTime got from this url
    //http://stackoverflow.com/questions/11560313/getting-info-from-api-using-json?rq=1

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
            //originally custom_component
        new Read().execute("Location");

    }

    private class Read extends AsyncTask<String, Integer, String> {

            protected String doInBackground(String... arg0) {
                // TODO Auto-generated method stub
                try {
                    JSONObject json = retrieveInfo(""); 
                    //create an instance of json object and make it to 
                    //the value returned by retrieveinfo method. Retrieveinfo passes nothing info because
                    //the URL that will be declared will not be modified
                    return json.getString(arg0[0]);
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String status) {
                super.onPostExecute(status);
                //pd.dismiss();

                AlertDialog alertDialog = new AlertDialog.Builder(
                        Main.this).create();
                alertDialog.setTitle("location");
                alertDialog.setMessage(status);
                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Main.this.finish();
                        dialog.cancel();
                    }
                });
                alertDialog.setIcon(android.R.drawable.ic_dialog_info);
                alertDialog.show();

            }


    public JSONObject retrieveInfo(String user) throws ClientProtocolException,
            IOException, JSONException {
        StringBuilder url = new StringBuilder(
                "http://10.0.0.1:1234/htdocs/android_project/all_location_array_display");
        //url.append(user);

        HttpClient httpclient = new DefaultHttpClient();
        HttpGet get = new HttpGet(url.toString());
        HttpResponse response = httpclient.execute(get);
        HttpEntity entity = response.getEntity();
        String data = EntityUtils.toString(entity);
        JSONObject timeline = new JSONObject(data);
        return timeline.getJSONObject("");
    }


    }

}


     <?php

//peliminary stuff
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();


//let us get all the rows out using mysqli_query
$result = mysql_query("SELECT * FROM location") or die(mysql_error());


//since we need to know if something is actually in the table we need to       //check this by using a if statement checking to see the number of rows

if(mysql_num_rows($result) > 0) {
//loop through the full table
//building a single object in the response array defined above
    $response["location"] = array();    

while($row = mysql_fetch_array($result)) {

//define a temporary array location_test[]
    $location_test = array();
 //now we need to fill in the location details using the variables           //from table
    $location_test["pid"] = $row["pid"];
    $location_test["time"] = $row["time"];
    $location_test["location"] = $row["location"];

// now that we an array that has the nescessary details,
//we need to push this into the $response array we defined to make 
//a single location entry for a certain time
    array_push($response["location"], $location_test);
}
echo json_encode($response);
}

?> 

1 个答案:

答案 0 :(得分:1)

要实现多个walker,您可以运行另一个循环(虽然这不是我建议的解决方案;请参阅建议的解决方案)。您可以创建一个空的二维numpy数组step_matrix = np.zeros((num_walkers, num_steps)),然后添加一个外部循环(内部循环填充每个col,外部循环移动到下一行)。

...
N = 10 #Number of Steps
d_avg = 0
nw = 2  # number of walkers
# Takes one step per second (Per N)
time = np.arange(N)
position = np.zeros(N)
walkers = np.zeros((nw, N))
for w in range(nw):
    for i in range (N-1):
        rn = np.random.uniform(0,1) # This generates a random number between (x,y)
        if rn < fwd:   # If the random number picked is >0.5
            step = 1 # move forward 1 step
        else:
            step = -1 # If the random number picked is not >0.5, then move backwards
        position[i+1]=position[i]+step
        d_avg+=position[i]
    walkers[w, :] = position
...

现在每行都有每个步行者的位置。

注意:Python和scipy / numpy已经有了处理这些事情的方法,但是不需要嵌套循环。

建议的解决方案:假设所有步行者都从0开始。

我会像这样编写多个walker:

import numpy as np
from __future__ import division  # to force division of int to float
num_walkers = 3  # change as needed
num_steps = 10   # change as needed
prob = 0.5

step_matrix = np.random.randint(2, size=(num_walkers, num_steps))
step_matrix[step_matrix < prob] = -1
print step_matrix

打印:

[[-1  1 -1 -1 -1  1  1 -1  1  1]
 [ 1  1 -1 -1  1 -1 -1  1  1 -1]
 [-1 -1  1  1  1 -1 -1 -1 -1  1]]

因此,在没有循环的情况下,这会给出一个数组,其中行是步行者,列是步骤。

注意:这些不是您跟踪时每个步骤的位置,而是每个步骤移动的方向。

你描述的是你想要的是什么听起来像均方误差(mse),所以我会尽我所能:

total_displacement = np.sum(step_matrix, axis=1).reshape(num_walkers, 1)
print total_displacement

打印:

[[ 0]
 [ 0]
 [-2]]

所以我们得到每个助行器的总位移,它只是沿着行的总和(步长的总和)。根据你的描述,我们需要从每个步骤中减去这个总位移,将这个值平方,然后将这些平方差异相加:

mse = np.sum(np.power((step_matrix - total_displacement), 2), axis=1).reshape(num_walkers,1)/num_steps

将这一切都放在一个功能中:

def random_walkers(n_walkers, n_steps, p):
    import numpy as np
    from __future__ import division  # to force division of int to float
    step_matrix = np.random.randint(2, size=(n_walkers, n_steps))
    step_matrix[step_matrix < p] = -1
    total_displacement = np.sum(step_matrix, axis=1).reshape(n_walkers, 1)
    positions = np.zeros((n_walkers, n_steps+1))
    for i in range(n_steps):
        positions[:, i+1] = step_matrix[:, i] + positions[:, i]
    mse = np.sum(np.power((step_matrix - total_displacement), 2), axis=1).reshape(n_walkers,1)/n_steps
    return step_matrix, mse, positions

mat, mse, pos = random_walkers(2, 5, 0.5)
print mat
print mse
print pos

打印:

[[ 1  1 -1 -1  1]
 [ 1 -1 -1  1  1]]
[[ 1.6]
 [ 1.6]]
[[ 0.  1.  2.  1.  0.  1.]
 [ 0.  1.  0. -1.  0.  1.]]

这里pos是你想要绘制的,因为它跟踪实际位置随着时间的推移。所以只需选择一个特定的行,你的情节就像你期望的那样。